Can't connect to MySQL database from C ++ program using MySQL Connector / C ++: exception thrown
I have a problem connecting to a MySQL database from a C ++ program:
std::string server, user, password;
SetParams(server, user, password);
boost::shared_ptr<sql::Connection> conn;
sql::Driver *driver = get_driver_instance();
if(driver == 0) { /* error; never reached */ }
try {
conn.reset(driver->connect(server, user, password));
assert(conn != 0);
if(!conn->isClosed()) // <-- exception thrown
{
// Connection established
}
else {
// Connection failed
}
}
catch (sql::SQLException &e)
{
cerr << e.what << e.getErrorCode() << e.getSQLState() << endl;
}
The function sql::Connection::isClosed()
throws this exception:
SQLException: Connection has been closed
MySQL error code: 0
SQLState: HY000
The values for server, user and password are correct (they work with MySQL-Workbench), the database is up and running.
I don't know where else to look ... Thanks.
Platform:
Linux - OpenSuse 11.4
MySQL 5.x
MySQL Connector / ++ 1.0.5
Update:
Since I read somewhere about possible conflicts between MySQL Connector / C ++ and Boost, I tried using a simple pointer instead of boost :: shared_ptr. Nothing changed.
Update 2:
Extract this code from the main program, the connection is successful.
I have to look at the big picture ...
source to share
Check this link http://dev.mysql.com/tech-resources/articles/mysql-connector-cpp.html#test
The problem is the connection you are creating with db
driver = get_driver_instance();
/* create a database connection using the Driver */
con = driver -> connect(url, user, password);
/* alternate syntax using auto_ptr to create the db connection */
//auto_ptr con (driver -> connect(url, user, password));
/* turn off the autocommit */
con -> setAutoCommit(0);
cout << "\nDatabase connection\ autocommit mode = " << con -> getAutoCommit() << endl;
/* select appropriate database schema */
con -> setSchema(database);
source to share