3

我有一个从 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-Workbench 连接),数据库已启动并正在运行。

我不知道在哪里看...
谢谢。

平台:
Linux - OpenSuse 11.4
MySQL 5.x
MySQL Connector/C++ 1.0.5


更新:
由于我在某处读到 MySQL Connector/C++ 和 Boost 之间可能存在的冲突,因此我尝试使用普通指针而不是 boost::shared_ptr。没有改变。


更新2:
将此代码隔离在主程序之外,连接成功。
我必须看大局...

4

2 回答 2

0

检查此链接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);
于 2013-02-05T10:57:28.647 回答
0

剪切并粘贴代码以在新的测试项目中访问数据库,一切正常。
不产生异常并建立连接。

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

于 2013-02-07T11:06:02.463 回答