Linux::mysql-connector-c++
1、安装好boost。
2、从官网下载mysql connector c++版本。
3、解压,复制 include/jdbc/cppconn 文件夹复制,到/usr/local/include/cppconn目录。,其他.h文件到到/usr/local/include/。
4、复制lib64中库文件到/usr/local/lib/目录中。
#include "mysql_connection.h" #include <cppconn/driver.h> #include <cppconn/exception.h> #include <cppconn/resultset.h> #include <cppconn/statement.h> #include <cppconn/prepared_statement.h> #include <stdio.h> using namespace std; int main(void) { sql::Driver *driver; sql::Connection *con; sql::Statement *stmt; sql::ResultSet *res; sql::PreparedStatement *pstmt; try { driver = get_driver_instance(); con = driver->connect("tcp://127.00.1:3306", "root", "command"); con->setSchema("viewfocus"); } catch (sql::SQLException &e) { printf("error \n"); } return 0; }
SRC += main.cpp GCC = g++ FLAG = -lmysqlcppconn CMS = CMS demo: $(GCC) -o $(CMS) -g $(SRC) $(FLAG) clean: rm CMS
CMysqlConnectPtr mysqlMgr::CreateConnection() { db_conf db = config::get_db_conf(); bool b_true = true; char strHonst[100] = { '\0' }; int nTime_out = 10; snprintf(strHonst, sizeof(strHonst), "tcp://%s:%s", db.strDBIP.c_str(), db.strDBPort.c_str()); spd::get("console")->info("{}", strHonst); sql::Connection *conn = driver->connect(strHonst, db.strDBUser.c_str(), db.strDBPswd.c_str()); conn->setClientOption("OPT_CONNECT_TIMEOUT", &nTime_out); conn->setClientOption("OPT_RECONNECT", &b_true); conn->setClientOption("CLIENT_MULTI_RESULTS", &b_true); conn->setClientOption("OPT_CHARSET_NAME", "utf8"); conn->setSchema(db.strDBName.c_str()); std::shared_ptr<sql::Connection> sp(conn,[](sql::Connection *conn) { delete conn; }); return sp; }
//************************************************************************* // 函数名称: SyncExecSQL // 返 回 值: bool --执行成功返回true, 否则返回false // 参 数: FUNCCALL fun --可以是回调函数,仿函数,lambda表达式 // 函数说明: 同步执行一个数据库操作, //************************************************************************* template<class FUNCCALL> bool SyncExecSQL(FUNCCALL fun) { bool bResult = false; CMysqlConnectPtr pDB = CreateConnection(); if (!pDB) { spd::get("console")->info("{} {} {}", __FILE__, __LINE__,"SyncExecSQL(FUNCCALL fun)"); return bResult; } try { fun(pDB); bResult = true; } catch (sql::SQLException &e) { spd::get("console")->info("{} {} {}", __FILE__, __LINE__, "sql::SQLException"); } catch (...) { } return true; }
void mysqlMgr::loadMonitor() { cleanMap(); string strSql = "SELECT Dev_Code, Video_Alarm_Type from m_monitor "; SyncExecSQL([&](CMysqlConnectPtr pDB) { try { std::unique_ptr<sql::PreparedStatement> pstmt(pDB->prepareStatement(strSql)); std::unique_ptr<sql::ResultSet> res(pstmt->executeQuery()); if (res) { while (res->next()) { int index = MYSQL_BASE_INDEX_1; string devCode = res->getString(++index); string alamType = res->getString(++index); add2Map(devCode, alamType); } } } catch (sql::SQLException &e) { return false; } return true; }); }