无法使用mysql ++连接到SQL数据库

时间:2013-12-28 22:06:23

标签: c++ mysql service mysql++

我一直在尝试在我的应用程序中使用mysql ++库(基于Windows x64),但我似乎无法连接到我的sql server。 一些信息:

我使用此代码连接到服务器:

mysqlpp::Connection conn(db, 0, user, pass, 3306);

这肯定有正确的数据。

然后,我的sql server是MySQL安装的标准服务。而且我很确定我使用的是标准设置。我可以使用MySql Workbench连接它,我编辑了一些新表,但我自己的程序似乎没有连接。

我阅读了文档,但我找不到任何可能暗示我无法连接的具体内容。

1 个答案:

答案 0 :(得分:1)

哦,这么多问题,这么短的时间......

您是否检查过您的程序是否有权访问数据库?

您的计划是否拥有正确的权限?

您的主机名是否正确?

你得到了什么错误?

抛出什么异常?

使用调试器时,错误在哪一行?

这是我的方法:

sql::Connection * const
Manager ::
get_db_connection(void) const
{
    //-------------------------------------------------------------------------
    //  Use only one connection until proven that more connections will make
    //      the program more efficient or have a beneficial impact on the user.
    //  Thus the change in returning sql::Connection * rather than a smart pointer.
    //      A smart pointer will delete its contents.
    //-------------------------------------------------------------------------
    static const char                   host_text[] = "tcp://127.0.0.1:3306/";
    static std::string                  host_name;
    if (!m_connection_initialized)
    {
        host_name = host_text;
        initialize_db_driver();
        host_name += m_dataset_info.m_dsn_name;
        try
        {
            m_p_connection = m_p_sql_driver->connect(host_name.c_str(),
                                                   m_dataset_info.m_user_name.c_str(),
                                                   m_dataset_info.m_password.c_str());
        }
        catch (sql::SQLException &e)
        {
            /*
            The MySQL Connector/C++ throws three different exceptions:

            - sql::MethodNotImplementedException (derived from sql::SQLException)
            - sql::InvalidArgumentException (derived from sql::SQLException)
            - sql::SQLException (derived from std::runtime_error)
            */
            wxString    wx_text = wxT("# ERR: SQLException in ");
            wx_text += wxT(__FILE__);
            wxLogDebug(wx_text);
            wx_text.Printf(wxT("# ERR: (%s) on line %d"),
                           __FUNCTION__,
                           __LINE__);
            wxLogDebug(wx_text);
            wx_text.Printf(wxT("# ERR: %s (MySQL error code: %d, SQLState: %s)"),
                e.what(),
                e.getErrorCode(),
                e.getSQLState());
            wxLogDebug(wx_text);
            wxLogDebug(wxT("Verify that mysqlcppconn.dll is in the PATH or in the working directory."));
            //      throw Manager_Connection_Not_Initialized();
            m_connection_initialized = false;
        }
        catch (...)
        {
            std::cout << "Unhandled database SQL exception\n" << flush;
            m_connection_initialized = false;
        }           
        m_connection_initialized = true;
    }
    return m_p_connection;
}