简体   繁体   中英

How to connect to MySQL database with C++ (ubuntu)

I'm not sure how to connect to a MySQL database using C++ on Ubuntu Linux. Specifically, I want to be able to create a database called " new ". I'm not sure where to put the query. Below is the code I'm using.

driver = get_driver_instance(); gives me the error message undefined reference to 'get_driver_instance'

#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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM