【问题标题】:Cannot connect to a MySQL database from a C++ program with MySQL Connector/C++: exception thrown无法使用 MySQL Connector/C++ 从 C++ 程序连接到 MySQL 数据库:抛出异常
【发布时间】:2013-01-20 05:34:41
【问题描述】:

我有一个从 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 连接器/C++ 1.0.5


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


更新 2:
将这段代码从主程序中隔离出来,连接成功。
我必须放眼大局……

【问题讨论】:

    标签: c++ mysql exception database-connection mysql-connector


    【解决方案1】:

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

    问题在于您使用 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\'s autocommit mode = " << con -> getAutoCommit() << endl;
        /* select appropriate database schema */
        con -> setSchema(database);
    

    【讨论】:

    • 考虑到在我的代码中,我在“// Connection established”块中调用了setAutoCommit()setSchema() 函数,唯一的区别在于我的conn.reset(driver-&gt;connect(...)); 与您的直接分配。我错了吗?
    • 是的,你是对的,这些是次要的,主要是 `conn.reset(driver->connect(...));'尝试更改该连接语句。
    • 我使用reset(),因为我使用的是共享指针。这是一项任务。
    • 你认为使用纯指针而不是boost::shared_ptrauto_ptr(就像MySQL 那样)会更好吗?
    【解决方案2】:

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

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

    【讨论】:

    • 不幸的是,这个解决方案对我不起作用。切换到一个新项目,甚至创建一个单独的函数来处理连接都没有帮助。我添加了更多细节here
    猜你喜欢
    • 1970-01-01
    • 2015-09-15
    • 1970-01-01
    • 2023-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-27
    • 2019-10-19
    相关资源
    最近更新 更多