背景
将基于c++图像处理后得到的数据更新到数据库
参考资料
Windows版
https://www.cnblogs.com/xiaoshiwang/p/11547900.html
https://cloud.tencent.com/developer/article/1764185
环境配置
sudo apt-get install libmysqlcppconn-dev
sudo apt install mysql-server
参考代码
#include <iostream>
#include <mysql_driver.h>
#include <mysql_connection.h>
#include <cppconn/statement.h>
#include <cppconn/prepared_statement.h>
int main()
{
try
{
sql::mysql::MySQL_Driver *driver; // MySQL 驱动
sql::Connection *con; // 连接对象
sql::PreparedStatement *pstmt; // 预处理语句对象
// 创建驱动
driver = sql::mysql::get_mysql_driver_instance();
// 建立连接(请替换为你的数据库用户名、密码、数据库名称)
con = driver->connect("tcp://127.0.0.1:3306", "root", "passwd");
// 连接到指定数据库
con->setSchema("database_name");
if(con->isValid()){
std::cout<<"connected!"<<std::endl;
}
// // 创建预处理语句
// pstmt = con->prepareStatement("INSERT INTO table_name (column1, column2) VALUES (?, ?)");
// // 绑定参数
// pstmt->setString(1, "value1");
// pstmt->setInt(2, 123);
// // 执行语句
// pstmt->execute();
// // 清理
delete pstmt;
delete con;
} catch (sql::SQLException &e) {
std::cerr << "MySQL 错误信息:" << e.what();
return 1;
} catch (std::runtime_error &e) {
std::cerr << "运行时错误:" << e.what();
return 1;
}
// std::cout << "数据写入成功!" << std::endl;
return 0;
}
编译
g++
g++ -o test test.cpp -lmysqlcppconn