环境配置
环境:windows10, visual studio 2019,已安装mysql server 版本为8.0.36,项目配置visual studio解决方案时,使用的Release x64
下载Mysql Connector/c++
mysql官方提供了connector/c++版本,connector是mysql官方提供的驱动数据库的工具(api),connector支持c++,提供库文件和头文件,来使用。
https://dev.mysql.com/downloads/connector/cpp/
此处下载了压缩包的版本 mysql-connector-c+±8.3.0-winx64
向项目中添加头文件和库文件(配置解决方案)
- 附加包含目录设置解压后的include路径:
- 附加库目录设置解压后的lib/64/vs14路径
- 附加依赖项设置
- 拷贝解压后的lib64目录下的所有.dll到与main函数文件同级的目录下 (或者放到.exe同级的目录也可以)
- 测试下如下代码能不能正常编译
#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<mysql/jdbc.h>#defineDBHOST"tcp://127.0.0.1:3306"#defineUSER"root"#definePASSWORD"123456"#defineDATABASE"sys"usingnamespace std;usingnamespace sql;intmain(){try{//连接数据库
Driver* driver =get_driver_instance();
Connection* conn = driver->connect(DBHOST, USER, PASSWORD);
Statement* stm;if(!conn->isValid()){
cout <<"数据库连接无效"<< endl;return0;}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;}return0;}
版权归原作者 Lution Young 所有, 如有侵权,请联系我们删除。