MySQL Connector/ODBC 是 MySQL 數(shù)據(jù)庫的官方C++驅(qū)動程序。
MySQL Connector/C++ 1.1.5 發(fā)布,此版本的二進制版本需要使用 Boost 1.54.0 編譯。
根據(jù)自己系統(tǒng)平臺下載相應(yīng)的版本。文件夾名字太長,將“mysql-connector-c++-noinstall-1.0.5-win32”改為“mysql”。
MySQL Connector/ODBC配置方法:
下面要配置vs2008的環(huán)境。
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文件夾下。
環(huán)境配置完畢。
數(shù)據(jù)庫使用:
在連接數(shù)據(jù)庫之前,先建立一張表。 (其實這些可以在代碼中完成,我這樣是為了讓測試代碼盡可能簡練易查錯)
打開控制臺,輸入mysql -u root -p,輸入密碼。
查看當前已有的數(shù)據(jù)庫。(SQL語句末尾加上';'表示立即執(zhí)行當前語句。)
mysql> show databases;
創(chuàng)建數(shù)據(jù)庫
mysql> create database test;
使用數(shù)據(jù)庫(這句不能加分號)
mysql> use test
查看已有的表
mysql> show tables;
創(chuàng)建表
mysql> create table testuser ( id INT, name CHAR(20));
插入數(shù)據(jù)
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');
現(xiàn)在在C++中查詢這些數(shù)據(jù)
#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;
// 初始化驅(qū)動
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傳入?yún)?shù)=====*/
..........
/*=====解析json傳入?yún)?shù),得到安裝碼或者id, 安裝時間, 硬盤序列號, ip,mac=====*/
..........
/*=====通過安裝碼找到數(shù)據(jù)庫中的對應(yīng)記錄寫入傳入的值=====*/
/********數(shù)據(jù)庫操作**********/
//1.得到數(shù)據(jù)庫連接
Connection* con = G<ConnectionPool>().GetConnection();
if (con == NULL)
{
LOG4CXX_ERROR(g_logger, "不能得到數(shù)據(jù)庫連接");
out.push_back(JSONNode(RESULT, ACTION_FALSE));
out.push_back(JSONNode(ERROR_MESSAGE, "不能得到數(shù)據(jù)庫連接"));
return false;
}
int ret = 1;
PreparedStatement* prep_stmt = NULL;
ResultSet* res = NULL;
try
{
con->setSchema(G<ConnectionPool>().GetDBName().c_str());
//執(zhí)行sql改變安裝狀態(tài)
std::string sql_statement = "update tb_host set reg_date=?, sn=?, ip=?, mac=?, state=?, sync_state=? where reg_code =? and state=?";//要執(zhí)行的sql語句
//事務(wù)處理
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;
}
//調(diào)用賦默認策略存儲過程
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, "數(shù)據(jù)庫異常" << e.what());
goto Finally_handle;
}
ret = 0;
LOG4CXX_ERROR(g_logger, "數(shù)據(jù)庫異常" << 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;
}
}
/************************************************************************/
/* 銷毀數(shù)據(jù)庫記錄集資源 */
/************************************************************************/
void CommonService::DestorySql(ResultSet* res, PreparedStatement* prep_stmt)
{
if (res != NULL)
{
try
{
res ->close();
}
catch(SQLException& e)
{
LOG4CXX_ERROR(g_logger, "數(shù)據(jù)庫異常" << e.what());
}
delete res;
res = NULL;
}
if (prep_stmt != NULL) {
try
{
prep_stmt->close();
}
catch(SQLException& e)
{
LOG4CXX_ERROR(g_logger, "數(shù)據(jù)庫異常" << e.what());
}
delete prep_stmt;
prep_stmt = NULL;
}
}
更新:
新增的特性和改進
Connector/C++ 支持以下的連接選項:sslVerify (boolean),sslCRL (string) 和sslCRLPath (string)。(Bug #18461451)
Connector/C++ 新增函數(shù)提供模式,表和列的字符集和結(jié)果集的校對元數(shù)據(jù) :(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 參數(shù)。(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)