MySQL连接在Ubuntu中抛出C++

MySQL连接在Ubuntu中抛出C++,mysql,Mysql,我已经安装了必要的软件包 sudoapt安装mysql服务器 sudo apt get安装libmysqlcppconn dev 这是我的密码: /* Standard C++ includes */ #include <stdlib.h> #include <iostream> /* Include directly the different headers from cppconn/ and mysql_driver.h + mysql_util.h

我已经安装了必要的软件包

sudoapt安装mysql服务器 sudo apt get安装libmysqlcppconn dev

这是我的密码:

/* Standard C++ includes */
#include <stdlib.h>
#include <iostream>

/*

  Include directly the different
  headers from cppconn/ and mysql_driver.h + mysql_util.h
  (and mysql_connection.h). This will reduce your build time!

*/
#include <mysql_connection.h>

#include <cppconn/driver.h>
#include <cppconn/exception.h>
#include <cppconn/resultset.h>
#include <cppconn/statement.h>

using namespace std;

int main(void)
{
cout << endl;
cout << "Running 'SELECT 'Hello World!'  AS _message'..." << endl;

try {
  sql::Driver *driver;
  sql::Connection *con;
  sql::Statement *stmt;
  sql::ResultSet *res;

  /* Create a connection */
  driver = get_driver_instance();
  con = driver->connect("tcp://127.0.0.1:11840", "root", "n");
/* Connect to the MySQL test database */
  con->setSchema("test");

  stmt = con->createStatement();
  res = stmt->executeQuery("SELECT 'Hello World!' AS _message"); // replace with your statement
  while (res->next()) {
    cout << "\t... MySQL replies: ";
    /* Access column data by alias or column name */
    cout << res->getString("_message") << endl;
    cout << "\t... MySQL says it again: ";
    /* Access column fata by numeric offset, 1 is the first column */
    cout << res->getString(1) << endl;
  }``
  delete res;
  delete stmt;
  delete con;

} catch (sql::SQLException &e) {
  cout << "# ERR: SQLException in " << __FILE__;
  //cout << "(" << __FUNCTION__ << ") on line " »
    // << __LINE__ << endl;
  cout << "# ERR: " << e.what();
  cout << " (MySQL error code: " << e.getErrorCode();
  cout << ", SQLState: " << e.getSQLState() << " )" << endl;
}

cout << endl;

return EXIT_SUCCESS;
}
它编译成功了

当我跑步时:

./testapp
正在运行“选择”Hello World作为“消息”

# ERR: SQLException in mysql_connect1.cpp# ERR: 
Can't connect to MySQL server on '127.0.0.1' (111) 
(MySQL error code: 2003, SQLState: HY000 )
我得到了上面的错误

我按照建议做了以下更改:

运行命令vim/etc/mysql/my.cnf 注释绑定地址=127.0.0.1,使用符号 重新启动mysql服务器一次。 但它仍然不起作用

产出:

root@knils-HP:/home/knils# sudo netstat -tap | grep mysql
tcp 0 0 *:mysql *:* LISTEN 11840/mysqld
root@knils-HP:/home/knils#

有人能帮我吗?

您确定您的服务器运行在11840上,并且您使用的用户帐户允许从本地主机连接吗

con = driver->connect("tcp://127.0.0.1:11840", "root", "n");
您的控制台输出看起来更像processID或内部端口。 MySQL通常在3306上运行,除非您自己更改了它

你能试试吗

con = driver->connect("tcp://127.0.0.1:3306", "root", "n");
?

con = driver->connect("tcp://127.0.0.1:3306", "root", "n");