记录使用Connector C++及VS2019连接数据库的过程
Step1:下载Mysql 8.0.29 Mysql官网下载地址,建议下载MSI安装程序同时,下载SourceCode,方便查看API的用法
Ps:官方Connector C++说明截取如下
On Windows platforms, Commercial and Community Connector/C++distributions require the Visual C++ Redistributable for VisualStudio. The Redistributable is available at the Visual Studio DownloadCenter; install it before installing Connector/C++. Theacceptable Redistributable versions depend on your Connector/C++version:
•Connector/C++ 8.0.19 and higher: VC++ Redistributable 2017 orhigher.
•Connector/C++ 8.0.14 to 8.0.18: VC++ Redistributable 2015 orhigher.
Step2:安装Mysql 8.0.29(安装之前需要安装python-3.10.4-amd64)
Step3:新建自己的工程
Step4:将Connector C++ 8.0\include目录下面的三个文件夹copy到自己的工程路径下面去,同时将Connector C++ 8.0\lib64目录下面所有的静态库以及动态库copy到自己工程路径下
Step5:配置工程属性,添加头文件包含,附加依赖项
Step6:直接上范例代码(这部分代码是网上查的直接用的别人的)
#include <iostream>
#include "jdbc/mysql_connection.h"
#include "jdbc/mysql_driver.h"
#include "jdbc/cppconn/statement.h"
#include "jdbc/cppconn/prepared_statement.h"
using namespace std;
using namespace sql;
int main()
{
sql::PreparedStatement* prep_stmt;
int updatecount = 0;
std::cout << "Hello World!\n";
std::cout << "test mysql\n";
sql::mysql::MySQL_Driver* driver = NULL;
sql::Connection* conn = NULL;
driver = sql::mysql::get_mysql_driver_instance();
if (driver == NULL)
{
std::cout <<"driver is null" << std::endl;
}
conn = driver->connect("tcp://localhost:3306", "root", "123456");
if (conn == NULL)
{
std::cout << "conn is null" << std::endl;
}
std::cout << "connect suceess" << std::endl;
//查询
int flag = 0;
sql::Statement* stmt = conn->createStatement();
sql::ResultSet* res;
res = stmt->executeQuery("SELECT * FROM cms_device");
while (res->next())
{
cout << res->getInt("id") << endl;
cout << res->getString("phone").c_str() << endl;
cout << res->getString("imsi").c_str() << endl;
}
//插入
conn->setAutoCommit(0);//关闭自动提交
res->first();
flag = 0;
while (res->next())
{
if (strcmp(res->getString("imsi").c_str(), "460010010000100") == 0)
{
flag = 1;
break;
}
}
if (flag == 0) {
prep_stmt = conn->prepareStatement("INSERT INTO cms_device (id,phone,imsi) VALUES (111,?,?)");
prep_stmt->setString(1, "15043214321");
prep_stmt->setString(2, "460010010000100");
updatecount = prep_stmt->executeUpdate();
}
Savepoint* savept;
savept = conn->setSavepoint("SAVEPT1");
res->first();
flag = 0;
while (res->next())
{
if (strcmp(res->getString("imsi").c_str(), "460010010000101") == 0)
{
flag = 1;
break;
}
}
if (flag == 0) {
prep_stmt = conn->prepareStatement("INSERT INTO cms_device (phone,imsi) VALUES (?,?)");
prep_stmt->setString(1, "15043214321");
prep_stmt->setString(2, "460010010000101");
updatecount = prep_stmt->executeUpdate();
}
conn->rollback(savept);
conn->releaseSavepoint(savept);
conn->commit();
//更新
conn->setAutoCommit(1);//打开自动提交
prep_stmt = conn->prepareStatement("update cms_device set phone=? where phone=?");
prep_stmt->setString(1, "15011111111");
prep_stmt->setString(2, "15043214321");
updatecount = prep_stmt->executeUpdate();
system("pause");
}