【问题标题】:Simple solutions for integrating MySQL with C++?将 MySQL 与 C++ 集成的简单解决方案?
【发布时间】:2012-07-13 00:22:17
【问题描述】:
有哪些解决方案可以在 C++ 中建立与 MySQL 数据库的简单连接?
我发现 dev.mysql.com 的 MySQL 连接器很难集成。
期待感谢!
【问题讨论】:
-
-
simple: connect -> query -> close,我的错,我也应该在“解决方案”之前提到 simple。似乎其他人同意集成 mySQL 连接器很痛苦r3dux.org/2010/11/… ...我的意思是,为什么 MySQL 安装手册没有提到需要 boost 库?
-
-
标签:
c++
mysql
database
integration
【解决方案1】:
从 C/C++ 应用程序与 MySQL 通信非常简单
你需要包含mysql.h头文件
连接和执行查询的三个基本 API
mysql_connect()
mysql_query()
mysql_close()
与 mysql 库 (libMysql) 的链接
【解决方案2】:
您可以尝试使用支持库的 ODBC 路径。
几年前,我使用OTL 连接SqlServer,发现它很高效。现在我尝试连接MySql,到目前为止没有任何问题:
#include <otlv4.h>
#include <iostream>
using namespace std;
int otl_x_sql_main(int argc, char **argv)
{
otl_connect db; // connect object
otl_connect::otl_initialize(); // initialize ODBC environment
try {
db.rlogon("DRIVER=mysql;DB=...;UID=...;PWD=..."); // connect to ODBC
// parametrized SELECT
otl_stream i(50, "SELECT product_id,model FROM product WHERE product_id >= :f<int> AND product_id < :ff<int>", db);
int product_id;
char model[100];
i << 1000 << 2000; // assigning product_id range
// SELECT automatically executes when all input variables are assigned
while (!i.eof()) {
i >> product_id >> model;
cout << "product_id=" << product_id << ", model=" << model << endl;
}
}
catch(otl_exception& p) { // intercept OTL exceptions
cerr << p.msg << endl; // print out error message
cerr << p.stm_text << endl; // print out SQL that caused the error
cerr << p.sqlstate << endl; // print out SQLSTATE message
cerr << p.var_info << endl; // print out the variable that caused the error
}
return 0;
}