c++ - 如何使用 C++ (ubuntu) 连接到 MySQL 数据库

标签 c++ mysql linux database ubuntu

我不确定如何在 Ubuntu Linux 上使用 C++ 连接到 MySQL 数据库。
具体来说,我希望能够创建一个名为“ new ”的数据库。我不确定在哪里放置查询。下面是我正在使用的代码。

驱动程序 = get_driver_instance(); 给我错误信息对“get_driver_instance”的 undefined reference

#include <cstdlib>
#include "mysql_driver.h"
#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(int argc, char** argv) {

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();
 /* Write your own driver details */
 con = driver->connect("tcp://127.0.0.1:3306", "root", "pass");
 /* Connect to the MySQL test database */
 con->setSchema("test");

 stmt = con->createStatement();
 res = stmt->executeQuery("SELECT 'Hello World!' AS _message");
 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 data 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 ";
  cout  << __LINE__ << endl;
  cout << "# ERR: " << e.what();
  cout << " (MySQL error code: " << e.getErrorCode();
  cout << ", SQLState: " << e.getSQLState() << " )" << endl;
}

 cout << endl;

 return EXIT_SUCCESS;
}

最佳答案

在你的终端上试试这个命令:

~# sudo g++ -Wall -I/usr/include/cppconn -o <output name> <codename.cpp> -L/usr/lib -lmysqlcppconn

关于c++ - 如何使用 C++ (ubuntu) 连接到 MySQL 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46088508/

相关文章:

python - 存储过程获取最后插入的行python mysql连接器

php - 这个 POST 和 PHP 是否可以正常工作以获取输入并将其发布到主服务器?

linux - 如何使用终端更改网络信息的 IP 地址?

linux - Linux 或任何其他类 UNIX 平台上 UDP 的 QOS

c++ - 关于使用链表在堆栈实现中的嵌套类

c++ - 在下面的程序中创建了多少个虚表?

c++ - OpenCV 与 ImageMagick?

c++ - clang++ 4.1,NULL 取消引用不会崩溃?

mysql - 在mysql字段的每一行中插入文本

linux - 无法重置 Chef 用户的 key 或密码 "missing update permission"