MySQL Connector/ODBC 是 MySQL 数据库的官方C++驱动程序。
MySQL Connector/C++ 1.1.5 发布,此版本的二进制版本需要使用 Boost 1.54.0 编译。
根据自己系统平台下载相应的版本。文件夹名字太长,将“mysql-connector-c++-noinstall-1.0.5-win32”改为“mysql”。
MySQL Connector/ODBC配置方法:
下面要配置vs2008的环境。
1. 项目属性页->C/C++->General->Additional Include Directories。将mysql\include目录添加进去。
2. 项目属性页->Linker->General->Additional Library Directories。将mysql\lib与$MySQL\bin目录添加进去。
3. 项目属性页->Linker->Input->Additional Dependencies。添加这两项mysqlcppconn.lib,mysqlcppconn-static.lib(mysql\lib目录下的两个.lib文件)
4. 将mysql\lib下的mysqlcppconn.dll文件与$MySQL\bin\libmySQL.dll复制到windows\system32文件夹下。
环境配置完毕。
数据库使用:
在连接数据库之前,先建立一张表。 (其实这些可以在代码中完成,我这样是为了让测试代码尽可能简练易查错)
打开控制台,输入mysql -u root -p,输入密码。
查看当前已有的数据库。(SQL语句末尾加上';'表示立即执行当前语句。)
mysql> show databases;
创建数据库
mysql> create database test;
使用数据库(这句不能加分号)
mysql> use test
查看已有的表
mysql> show tables;
创建表
mysql> create table testuser ( id INT, name CHAR(20));
插入数据
mysql> insert into testuser(id, name) values(1001, 'google');
mysql> insert into testuser(id, name) values(1002, 'kingsoft');
mysql> insert into testuser(id, name) values(1003, 'firefox');
现在在C++中查询这些数据
#include "stdafx.h"
#include <mysql_connection.h>
#include <mysql_driver.h>
#include <statement.h>
using namespace sql;
using namespace std;
void RunConnectMySQL()
{
mysql::MySQL_Driver *driver;
Connection *con;
Statement *state;
ResultSet *result;
// 初始化驱动
driver = sql::mysql::get_mysql_driver_instance();
// 建立链接
con = driver->connect("tcp://127.0.0.1:3306", "root", "123");
state = con->createStatement();
state->execute("use test");
// 查询
result = state->executeQuery("select * from testuser where id < 1002");
// 输出查询
while(result->next())
{
int id = result->getInt("ID");
string name = result->getString("name");
cout << id << " : " << name << endl;
}
delete state;
delete con;
}
int _tmain(int argc, _TCHAR* argv[])
{
RunConnectMySQL();
getchar();
return 0;
}
接口实例:
bool CommonService::......(JSONNode& in, JSONNode& out)
{
/*=====校验json传入参数=====*/
..........
/*=====解析json传入参数,得到安装码或者id, 安装时间, 硬盘序列号, ip,mac=====*/
..........
/*=====通过安装码找到数据库中的对应记录写入传入的值=====*/
/********数据库操作**********/
//1.得到数据库连接
Connection* con = G<ConnectionPool>().GetConnection();
if (con == NULL)
{
LOG4CXX_ERROR(g_logger, "不能得到数据库连接");
out.push_back(JSONNode(RESULT, ACTION_FALSE));
out.push_back(JSONNode(ERROR_MESSAGE, "不能得到数据库连接"));
return false;
}
int ret = 1;
PreparedStatement* prep_stmt = NULL;
ResultSet* res = NULL;
try
{
con->setSchema(G<ConnectionPool>().GetDBName().c_str());
//执行sql改变安装状态
std::string sql_statement = "update tb_host set reg_date=?, sn=?, ip=?, mac=?, state=?, sync_state=? where reg_code =? and state=?";//要执行的sql语句
//事务处理
con->setAutoCommit(0);
prep_stmt = con->prepareStatement(sql_statement.c_str());
prep_stmt->setString(1, install_time.c_str());
prep_stmt->setString(2, harddrive_sn.c_str());
prep_stmt->setString(3, ip_address.c_str());
prep_stmt->setString(4, mac_address.c_str());
prep_stmt->setInt(5, HAS_INSTALL);
prep_stmt->setInt(6, HAS_SYNC);
prep_stmt->setString(7, install_code.c_str());
prep_stmt->setInt(8, NO_INSTALL);
if(prep_stmt->executeUpdate() == 0)
{
ret = 2;
LOG4CXX_INFO(g_logger, ".....");
out.push_back(JSONNode(ERROR_MESSAGE, "....."));
goto Finally_handle;
}
//调用赋默认策略存储过程
std::string procedure = "CALL updateHostPolicyByModHost(?,?, @ret, @msg)";
prep_stmt = con->prepareStatement(procedure.c_str());
prep_stmt->setString(1, install_code.c_str());
prep_stmt->setInt(2, 0);
prep_stmt->execute();
std::string query = "select @ret AS ret,@msg AS msg";
prep_stmt = con->prepareStatement(query.c_str());
res = prep_stmt->executeQuery();
while(res->next())
{
if(res->getInt("ret") != 0)
{
LOG4CXX_ERROR(g_logger, "....." << res->getString("msg").c_str() << res->getInt("ret"));
out.push_back(JSONNode(ERROR_MESSAGE, "....."));
goto Finally_handle;
}
}
con ->commit();
}
catch (SQLException& e)
{
try
{
con->rollback();
}
catch (SQLException& e)
{
ret = 0;
LOG4CXX_ERROR(g_logger, "数据库异常" << e.what());
goto Finally_handle;
}
ret = 0;
LOG4CXX_ERROR(g_logger, "数据库异常" << e.what());
out.push_back(JSONNode(ERROR_MESSAGE, e.what()));
goto Finally_handle;
}
catch (...)
{
ret = 0;
LOG4CXX_ERROR(g_logger, "其他错误");
out.push_back(JSONNode(ERROR_MESSAGE, "其他错误"));
goto Finally_handle;
}
Finally_handle:
DestorySql(res, prep_stmt);
//将连接释放到连接池
G<ConnectionPool>().ReleaseConnection(con);
if (ret == 1)
{
out.push_back(JSONNode(RESULT, ACTION_SUCCESS));
return true;
}
else if (ret == 2)
{
out.push_back(JSONNode(RESULT, ACTION_FALSE));
return true;
}
else
{
out.push_back(JSONNode(RESULT, ACTION_FALSE));
return false;
}
}
/************************************************************************/
/* 销毁数据库记录集资源 */
/************************************************************************/
void CommonService::DestorySql(ResultSet* res, PreparedStatement* prep_stmt)
{
if (res != NULL)
{
try
{
res ->close();
}
catch(SQLException& e)
{
LOG4CXX_ERROR(g_logger, "数据库异常" << e.what());
}
delete res;
res = NULL;
}
if (prep_stmt != NULL) {
try
{
prep_stmt->close();
}
catch(SQLException& e)
{
LOG4CXX_ERROR(g_logger, "数据库异常" << e.what());
}
delete prep_stmt;
prep_stmt = NULL;
}
}
更新:
新增的特性和改进
Connector/C++ 支持以下的连接选项:sslVerify (boolean),sslCRL (string) 和sslCRLPath (string)。(Bug #18461451)
Connector/C++ 新增函数提供模式,表和列的字符集和结果集的校对元数据 :(Bug #72698, Bug #18803345)
ResultSet * DatabaseMetaData::getSchemaCollation(const sql::SQLString& catalog, const sql::SQLString&schemaPattern)
ResultSet * DatabaseMetaData::getSchemaCharset(const sql::SQLString& catalog, const sql::SQLString& schemaPattern)
ResultSet * DatabaseMetaData::getTableCollation(const sql::SQLString& catalog, const sql::SQLString&schemaPattern,const sql::SQLString&tableNamePattern)
ResultSet * DatabaseMetaData::getTableCharset(const sql::SQLString& catalog, const sql::SQLString&schemaPattern, const sql::SQLString&tableNamePattern)
SQLString ResultSetMetaData::getColumnCollation(unsigned int columnIndex)
SQLString ResultSetMetaData::getColumnCharset(unsigned int columnIndex)
Connector/C++ 支持 MYSQL_OPT_CONNECT_ATTR_ADD 选项,能接收一个 std::map 参数。(Bug #72697, Bug #18803313)
Connector/C++ 支持一个 useLegacyAuth 连接选项 (Bug #69492, Bug #16970753)
Connector/C++ 编译和链接到 Connector/C 6.1.5 而不是 libmysql
Bugs 修复
MySQL_ResultSetMetaData::getColumnTypeName()returned UNKNOWN for LONG_BLOB fields. (Bug #72700, Bug #18803414)
Connector/C++ version-information methods have been revised to return the correct values. (Bug #66975, Bug #14680878)
Definitions for character sets and collations were added (utf8mb4 in particular). (Bug #71606, Bug #18193771)