无法从带有MySQL连接器/C++的C++程序连接到MySQL数据库:引发异常

Cannot connect to a MySQL database from a C++ program with MySQL Connector/C++: exception thrown

本文关键字:MySQL C++ 数据库 连接 异常 程序 连接器      更新时间:2023-10-16

我有一个从C++程序到MySQL数据库的连接问题:

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;
}

sql::Connection::isClosed()函数抛出以下异常:

SQLException: Connection has been closed  
MySQL error code: 0  
SQLState: HY000

服务器、用户和密码的值是正确的(它们从MySQL工作台连接),数据库已经启动并运行。

我不知道还能去哪里看
非常感谢。

平台:
Linux-OpenSuse 11.4
MySQL 5.x
MySQL连接器/C++1.0.5


更新:
由于我在某些地方读到了MySQL连接器/C++和Boost之间可能存在的冲突,我尝试使用纯指针而不是Boost::shared_ptr。一切都没有改变。


更新2:
将此代码从主程序中隔离出来,连接就成功完成了
我必须着眼于大局。。。

检查此链接http://dev.mysql.com/tech-resources/articles/mysql-connector-cpp.html#test

问题是你用数据库创建的连接

    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's autocommit mode = " << con -> getAutoCommit() << endl;
    /* select appropriate database schema */
    con -> setSchema(database);

在新的测试项目中剪切和粘贴代码以访问数据库,一切都很好
未生成任何异常,并且已建立连接。

这意味着我必须看看项目的其余部分会发生什么。