sql::Connection * per Pointer an Funktion übergeben
-
Hallo zusammen,
ich möchte eine Funktion um eine Verbindung zu MySQL herzustellen.
Ziel ist es die Variable "con" per Pointer an die Funktion zu übergeben.Folgende Fehlermeldung liefert mir der Compiler. Als IDE verwende ich VS2017.
Fehler C4700 Die nicht initialisierte lokale Variable "con" wurde verwendet.
Wie bekomme ich meine Vorstellung umgesetzt?
Danke schonmal#include <cstdlib> #include <stdio.h> #include <iostream> #include "mysql_connection.h" #include <cppconn/driver.h> #include <cppconn/exception.h> #include <cppconn/resultset.h> #include <cppconn/statement.h> #ifdef __unix__ #include <unistd.h> #elif defined(_WIN32) || defined(WIN32) #include <windows.h> #define OS_Windows #endif using namespace std; void mysql_verbinden(sql::Connection *con, std::string ip = "172.0.0.1") { sql::Driver *driver; try { /* Create a connection */ driver = get_driver_instance(); con = driver->connect("tcp://" + ip + ":3306", "root", ""); } catch (sql::SQLException &e) { cout << "# ERR: SQLException in " << __FILE__; cout << "(" << __FUNCTION__ << ") on line " << __LINE__ << endl; cout << "# ERR: " << e.what(); cout << " (MySQL error code: " << e.getErrorCode(); cout << ", SQLState: " << e.getSQLState() << " )" << endl; } return; } int main(int argc, char** argv) { cout << endl; cout << "Running 'SELECT 'Hello World!' » AS _message'..." << endl; try { sql::Connection *con; sql::Statement *stmt; sql::ResultSet *res; // Verbindung aufbauen mysql_verbinden(con); stmt = con->createStatement(); res = stmt->executeQuery("SELECT 'Hello World!' AS _message"); while (res->next()) { cout << "\t... MySQL replies: "; /* Access column data by alias or column name */ cout << res->getString("_message") << endl; cout << "\t... MySQL says it again: "; /* Access column data by numeric offset, 1 is the first column */ cout << res->getString(1) << endl; } delete res; delete stmt; delete con; } catch (sql::SQLException &e) { cout << "# ERR: SQLException in " << __FILE__; cout << "(" << __FUNCTION__ << ") on line " << __LINE__ << endl; cout << "# ERR: " << e.what(); cout << " (MySQL error code: " << e.getErrorCode(); cout << ", SQLState: " << e.getSQLState() << " )" << endl; } cout << endl; boost::detail::Sleep(5000); return 0; }
-
setz den pointer vorher auf null
-
Das hilft auch nicht. Der Fehler ist, daß in der Funktion mysql_verbinden der Parameter nur als einfacher Zeiger (nicht als Doppelzeiger bzw. Referenz übergeben wird).
Besser wäre aber, den Zeiger als Rückgabewert der Funktion zu benutzen:sql::Connection* mysql_verbinden(std::string ip = "172.0.0.1") { sql::Connection *con; // ... return con; }
-
Verwende eine Referenz.
void mysql_verbinden(sql::Connection* &con, std::string ip = "172.0.0.1") {