环境:windows10, visual studio 2019,已安装mysql server 版本为8.0.36,项目配置visual studio解决方案时,使用的Release x64
mysql官方提供了connector/c++版本,connector是mysql官方提供的驱动数据库的工具(api),connector支持c++,提供库文件和头文件,来使用。
https://dev.mysql.com/downloads/connector/cpp/
此处下载了压缩包的版本 mysql-connector-c+±8.3.0-winx64
#include "jdbc/mysql_driver.h" #include "jdbc/mysql_connection.h" #include "jdbc/cppconn/driver.h" #include "jdbc/cppconn/connection.h" #include "jdbc/cppconn/statement.h" #include "jdbc/cppconn/prepared_statement.h" #include "jdbc/cppconn/resultset.h" #include "jdbc/cppconn/metadata.h" #include "jdbc/cppconn/resultset_metadata.h" #include "jdbc/cppconn/exception.h" #include "jdbc/cppconn/warning.h" #include#define DBHOST "tcp://127.0.0.1:3306" #define USER "root" #define PASSWORD "123456" #define DATABASE "sys" using namespace std; using namespace sql; int main() { try { //连接数据库 Driver* driver = get_driver_instance(); Connection* conn = driver->connect(DBHOST, USER, PASSWORD); Statement* stm; if (!conn->isValid()) { cout << "数据库连接无效" << endl; return 0; } else cout << "数据库连接成功" << endl; //创建 test 表,添加数据 stm = conn->createStatement(); stm->execute("use " DATABASE); stm->execute("DROP TABLE IF EXISTS test"); stm->execute("CREATE TABLE test(id INT,lable CHAR(1))"); stm->execute("INSERT INTO test(id,lable) VALUES(6,'A')"); stm->execute("INSERT INTO test(id,lable) VALUES(3,'A')"); stm->execute("INSERT INTO test(id,lable) VALUES(2,'A')"); //升序查询 ResultSet* rss; rss = stm->executeQuery("SELECT id,lable FROM test ORDER BY id ASC"); while (rss->next()) { /* code */ int id = rss->getInt(1); string lable = rss->getString("lable"); cout << "id:" << id << "," << "lable:" << lable << endl; } //删除 stm->execute("DELETE FROM test WHERE id=3"); //改 stm->execute("UPDATE test SET lable='B' WHERE id=2"); delete stm; delete conn; delete rss; } catch (const SQLException& sqle) { cout << "# ERR: SQLException in " << __FILE__; cout << "(" << __FUNCTION__ << ") on line " << __LINE__ << endl; std::cerr << "sql errcode:" << sqle.getErrorCode() << ",state:" << sqle.getSQLState() << ",what:" << sqle.what() << endl; } return 0; }