1.下載最新的Connector
https://dev.mysql.com/downloads/connector/cpp/,下載帶debug的庫。
解壓縮到本地,本次使用的是帶debug模式的connector庫:
注:其中mysqlcppconn與mysqlcppconn8的區別是:
2.在cmakelist中定義尋址頭文件的路徑與庫的路徑
#定義頭文件需要尋址的路徑
include_directories(D:/Library/mysql-connector-c++-8.2.0-winx64/include/jdbc
)#定義庫文件需要尋址的路徑
link_directories(D:/Library/mysql-connector-c++-8.2.0-winx64/lib64/vs14/debug
)target_link_libraries(QtDemo2Qt5::CoreQt5::GuiQt5::Widgets......mysqlcppconn
)
3.復制對應的DLL到可執行目錄
把D:\Library\mysql-connector-c+±8.2.0-winx64\lib64\debug中的mysqlcppconn-9-vs14.dll復制到項目的可執行目錄下。
3.基礎使用
https://dev.mysql.com/doc/connector-cpp/1.1/en/connector-cpp-examples-connecting.html
#include "sql_connector.h"
#include "string"
#include <QDebug>#include "mysql_connection.h"
#include "cppconn/driver.h"
#include "cppconn/exception.h"
#include "cppconn/prepared_statement.h"void SqlConnector::process()
{qDebug("SqlConnector started....");std::string server = "tcp://localhost:3306";std::string username = "root";std::string password = "Xi1ozh#1";sql::Driver* driver;sql::Connection* connection;try{driver = get_driver_instance();connection = driver->connect(server, username, password);connection->setSchema("ws300");}catch (sql::SQLException e){std::cout << "Could not connect to server. Error message: " << e.what() << "\n";}//查詢sql::SQLString sql("select * from users;");std::unique_ptr<sql::Statement> statment(connection->createStatement());statment->execute("set names utf8mb4");std::unique_ptr<sql::ResultSet> result(statment->executeQuery(sql));while (result->next()){auto data = result->getString("password").asStdString();qDebug("SqlConnector username: %s", data.c_str());}result->close();statment->close();connection->close();delete connection;qDebug("SqlConnector finished....");
}