博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
MySql C++调用库Connector/c++编译 和 接口封装【三】Connector/c++ 使用总结及封装
阅读量:5286 次
发布时间:2019-06-14

本文共 15979 字,大约阅读时间需要 53 分钟。

工程需要加上各个路径:

库使用需要几个文件:   1、include 文件夹   c/c++ /常规/附加包含目录    Connector/c++ 的安装版里面的Include 文件夹。或者把  /driver以及/driver/nativeapi 里面的头文件拷贝到一个文件夹里面(注意nativeapi要改名为 cppconn)。   2、Connector/c++ 库文件 和 MySql库文件:     2.1、mysqlcppconn.dll   /debug,exe生成目录     2.2、mysqlcppconn.lib   链接器/输入/附加依赖项     2.3、libmysql.dll    /debug    3、boost库所在目录   c/c++/常规/附加包含目录

 

头文件 MySqlDataBase.h :

#ifndef __MYSQL_DATABASE_H#define __MYSQL_DATABASE_H#include "mysql_connection.h"#include "mysql_driver.h"#include "cppconn/prepared_statement.h"#include "cppconn/statement.h"#include typedef boost::scoped_ptr
Connection;typedef boost::scoped_ptr
PreparedStatement;typedef boost::scoped_ptr
Statement;typedef boost::shared_ptr
ResultSet;typedef sql::mysql::MySQL_Driver MySQL_Driver;//mysql 错误类class CMySqlError{ //存储变量protected: int m_ErrorCode; std::string m_strErrorDescribe; public: //构造函数 CMySqlError(); //析构函数 ~CMySqlError();public: //获取ErrorCode int getErrorCode(){ return m_ErrorCode; } //错误描述 std::string GetErrorDestribe(){ return m_strErrorDescribe; }public: //设置错误 void SetErrorInfo(sql::SQLException &e);};class CMySqlDataBase{ //信息变量protected: CMySqlError m_MySqlError; //当前错误信息 std::map
m_ConnectProperties; //连接信息 //状态变量protected: const unsigned int m_dwTryConnectTimes; //连接变量protected: Connection m_DBConnect; PreparedStatement m_DBPrepareState; ResultSet m_DBRecordSet; //函数定义public: //构造函数 CMySqlDataBase(); //析构函数 ~CMySqlDataBase(); //管理接口public: //打开连接 bool OpenConnect(); //关闭记录 bool CloseRecordset(); //关闭连接 bool CloseConnect(); //重新连接(未实现) bool TryConnectAgain(); //设置信息 bool SetConnectionInfo(const std::string &hostIp,unsigned short hostPort,const std::string &dataBaseName,const std::string &userName,const std::string &password); //状态接口(未实现)public: //是否连接错误 bool IsConnectError(); //是否打开 bool IsRecordsetOpened(); //public: //准备prepareState bool PreparedExcute(const std::string &szCommand); bool setBigInt(unsigned int parameterIndex, const std::string& value); bool setBlob(unsigned int parameterIndex, std::istream * blob); //长文本字符串 bool setBoolean(unsigned int parameterIndex, bool value); bool setDateTime(unsigned int parameterIndex, const std::string& value); bool setDouble(unsigned int parameterIndex, double value); bool setInt(unsigned int parameterIndex, int32_t value); bool setUInt(unsigned int parameterIndex, uint32_t value); bool setInt64(unsigned int parameterIndex, int64_t value); bool setUInt64(unsigned int parameterIndex, uint64_t value); bool setString(unsigned int parameterIndex, const std::string& value); bool setNull(unsigned int parameterIndex, int sqlType); //执行命令(存储过程) bool ExecuteCommand(bool bRecordset); //执行语句接口public: //执行查询(Select) bool Query(const std::string &szCommand); //执行语句(Insert,Update,Delete) bool Execute(const std::string &szCommand); //字段接口 /* next() must been used before getdata */public: //获取当前 Result set const ResultSet &GetRecordSet(); //get Next Record set bool GetNextResultSet(); //move resultset to the nth result in the set bool NextFieldExist(); //获取参数 bool GetFieldValue(const std::string& columnLabel,bool &bValue); //获取参数 bool GetFieldValue(const std::string& columnLabel,long double &dbValue); //获取参数 bool GetFieldValue(const std::string& columnLabel,int32_t &nValue); //获取参数 bool GetFieldValue(const std::string& columnLabel,uint32_t &uValue); //获取参数 bool GetFieldValue(const std::string& columnLabel,int64_t &llValue); //获取参数 bool GetFieldValue(const std::string& columnLabel,uint64_t &lluValue); //获取参数 bool GetFieldValue(const std::string& columnLabel,char szBuffer[],uint32_t uSize); //获取参数 bool GetFieldValue(const std::string& columnLabel,std::string &szValue); //获取参数 //bool GetFieldValue(const std::string& columnLabel,SYSTEMTIME &systime); //内部函数private: //设置错误 void SetErrorInfo(sql::SQLException &e);};#endif

 

源文件MySqlDataBase.cpp

#include "MySqlDataBase.h"#include 
CMySqlError::CMySqlError(){}CMySqlError::~CMySqlError(){}void CMySqlError::SetErrorInfo(sql::SQLException &e){ m_ErrorCode = e.getErrorCode(); m_strErrorDescribe = e.what(); throw this;}CMySqlDataBase::CMySqlDataBase():m_DBConnect(NULL),m_DBPrepareState(NULL),m_DBRecordSet((sql::ResultSet*)NULL),m_dwTryConnectTimes(1){ }CMySqlDataBase::~CMySqlDataBase(){ try { CloseConnect(); m_DBRecordSet.reset((sql::ResultSet*)NULL); m_DBPrepareState.reset(NULL); m_DBConnect.reset(NULL); } catch(sql::SQLException &e) { SetErrorInfo(e);}}//设置错误void CMySqlDataBase::SetErrorInfo(sql::SQLException &e){ m_MySqlError.SetErrorInfo(e);}//打开连接bool CMySqlDataBase::OpenConnect(){ //建立连接 try { sql::mysql::MySQL_Driver *driver = sql::mysql::get_mysql_driver_instance(); m_DBConnect.reset(driver->connect(m_ConnectProperties["hostName"],m_ConnectProperties["userName"],m_ConnectProperties["password"])); m_DBConnect->setSchema(m_ConnectProperties["schema"]); } catch(sql::SQLException &e) { SetErrorInfo(e);} return true;}//关闭记录bool CMySqlDataBase::CloseRecordset(){ try { if(m_DBPrepareState != NULL) { while(m_DBPrepareState->getMoreResults()) m_DBRecordSet.reset(m_DBPrepareState->getResultSet()); m_DBPrepareState.reset(NULL); } if(m_DBRecordSet != NULL) m_DBRecordSet.reset((sql::ResultSet*)NULL); return true; } catch (sql::SQLException &e) { SetErrorInfo(e);} return false;}//关闭连接bool CMySqlDataBase::CloseConnect(){ try { CloseRecordset(); //close connect if(m_DBConnect != NULL) { m_DBConnect.reset(NULL); } return true; } catch (sql::SQLException &e) { SetErrorInfo(e);} return false;}//设置信息bool CMySqlDataBase::SetConnectionInfo(const std::string &hostIp,unsigned short hostPort,const std::string &dataBaseName,const std::string &userName,const std::string &password){ try { std::stringstream hostss; hostss<<"tcp://"<
<<":"<
isClosed()) return false; return true;}//准备prepareStatebool CMySqlDataBase::PreparedExcute(const std::string &szCommand){ if(szCommand.empty()) return false; //close RecordSet; CloseRecordset(); try { m_DBPrepareState.reset(m_DBConnect->prepareStatement(szCommand)); m_DBPrepareState->clearParameters(); return true; } catch (sql::SQLException &e) { SetErrorInfo(e);} return false;}bool CMySqlDataBase::setBigInt(unsigned int parameterIndex, const std::string& value){ try { m_DBPrepareState->setBigInt(parameterIndex,value); return true; } catch (sql::SQLException &e) { SetErrorInfo(e);} return false;}bool CMySqlDataBase::setBlob(unsigned int parameterIndex, std::istream * value) //长文本字符串{ try { m_DBPrepareState->setBlob(parameterIndex,value); return true; } catch (sql::SQLException &e) { SetErrorInfo(e);} return false;}bool CMySqlDataBase::setBoolean(unsigned int parameterIndex, bool value){ try { m_DBPrepareState->setBoolean(parameterIndex,value); return true; } catch (sql::SQLException &e) { SetErrorInfo(e);} return false;}bool CMySqlDataBase::setDateTime(unsigned int parameterIndex, const std::string& value){ try { m_DBPrepareState->setDateTime(parameterIndex,value); return true; } catch (sql::SQLException &e) { SetErrorInfo(e);} return false;}bool CMySqlDataBase::setDouble(unsigned int parameterIndex, double value){ try { m_DBPrepareState->setDouble(parameterIndex,value); return true; } catch (sql::SQLException &e) { SetErrorInfo(e);} return false;}bool CMySqlDataBase::setInt(unsigned int parameterIndex, int32_t value){ try { m_DBPrepareState->setInt(parameterIndex,value); return true; } catch (sql::SQLException &e) { SetErrorInfo(e);} return false;}bool CMySqlDataBase::setUInt(unsigned int parameterIndex, uint32_t value){ try { m_DBPrepareState->setUInt(parameterIndex,value); return true; } catch (sql::SQLException &e) { SetErrorInfo(e);} return false;}bool CMySqlDataBase::setInt64(unsigned int parameterIndex, int64_t value){ try { m_DBPrepareState->setInt64(parameterIndex,value); return true; } catch (sql::SQLException &e) { SetErrorInfo(e);} return false;}bool CMySqlDataBase::setUInt64(unsigned int parameterIndex, uint64_t value){ try { m_DBPrepareState->setUInt64(parameterIndex,value); return true; } catch (sql::SQLException &e) { SetErrorInfo(e);} return false;}bool CMySqlDataBase::setString(unsigned int parameterIndex, const std::string& value){ try { m_DBPrepareState->setString(parameterIndex,value); return true; } catch (sql::SQLException &e) { SetErrorInfo(e);} return false;}bool CMySqlDataBase::setNull(unsigned int parameterIndex, int sqlType){ try { m_DBPrepareState->setNull(parameterIndex,sqlType); return true; } catch (sql::SQLException &e) { SetErrorInfo(e);} return false;}//执行命令(存储过程)bool CMySqlDataBase::ExecuteCommand(bool bRecordset){ try { m_DBPrepareState->executeUpdate(); if(bRecordset) m_DBRecordSet.reset(m_DBPrepareState->getResultSet()); return true; } catch (sql::SQLException &e) { SetErrorInfo(e);} return false;}//执行查询(Select)bool CMySqlDataBase::Query(const std::string &szCommand){ if(szCommand.empty()) return false; //close RecordSet; CloseRecordset(); try { m_DBPrepareState.reset(m_DBConnect->prepareStatement(szCommand)); m_DBPrepareState->executeUpdate(); m_DBRecordSet.reset(m_DBPrepareState->getResultSet()); return true; } catch (sql::SQLException &e) { SetErrorInfo(e);} return false;}//执行语句(Insert,Update,Delete)bool CMySqlDataBase::Execute(const std::string &szCommand){ if(szCommand.empty()) return false; //close RecordSet; CloseRecordset(); try { m_DBPrepareState.reset(m_DBConnect->prepareStatement(szCommand)); m_DBPrepareState->executeUpdate(); return true; } catch (sql::SQLException &e) { SetErrorInfo(e);} return false;}//获取当前 Result setconst ResultSet &CMySqlDataBase::GetRecordSet(){ return m_DBRecordSet;}//get Next Record setbool CMySqlDataBase::GetNextResultSet(){ if(m_DBPrepareState == NULL) return false; if(m_DBPrepareState->getMoreResults()) { m_DBRecordSet.reset(m_DBPrepareState->getResultSet()); return true; } return false;}//nextbool CMySqlDataBase::NextFieldExist(){ if(m_DBRecordSet == NULL) return false; return m_DBRecordSet->next();}//获取参数bool CMySqlDataBase::GetFieldValue(const std::string& columnLabel,bool &bValue){ bValue = false; if(!IsRecordsetOpened()) return false; try { bValue = m_DBRecordSet->getBoolean(columnLabel); return true; } catch (sql::SQLException &e) { SetErrorInfo(e);} return false;}//获取参数bool CMySqlDataBase::GetFieldValue(const std::string& columnLabel,long double &dbValue){ dbValue = 0.00; if(!IsRecordsetOpened()) return false; try { dbValue = m_DBRecordSet->getDouble(columnLabel); return true; } catch (sql::SQLException &e) { SetErrorInfo(e);} return false;}//获取参数bool CMySqlDataBase::GetFieldValue(const std::string& columnLabel,int32_t &nValue){ nValue = 0; if(!IsRecordsetOpened()) return false; try { nValue = m_DBRecordSet->getInt(columnLabel); return true; } catch (sql::SQLException &e) { SetErrorInfo(e);} return false;}//获取参数bool CMySqlDataBase::GetFieldValue(const std::string& columnLabel,uint32_t &uValue){ uValue = 0; if(!IsRecordsetOpened()) return false; try { uValue = m_DBRecordSet->getUInt(columnLabel); return true; } catch (sql::SQLException &e) { SetErrorInfo(e);} return false;}//获取参数bool CMySqlDataBase::GetFieldValue(const std::string& columnLabel,int64_t &llValue){ llValue = 0; if(!IsRecordsetOpened()) return false; try { llValue = m_DBRecordSet->getInt64(columnLabel); return true; } catch (sql::SQLException &e) { SetErrorInfo(e);} return false;}//获取参数bool CMySqlDataBase::GetFieldValue(const std::string& columnLabel,uint64_t &lluValue){ lluValue = 0; if(!IsRecordsetOpened()) return false; try { lluValue = m_DBRecordSet->getUInt64(columnLabel); return true; } catch (sql::SQLException &e) { SetErrorInfo(e);} return false;}//获取参数bool CMySqlDataBase::GetFieldValue(const std::string& columnLabel,char szBuffer[],uint32_t uSize){ memset(szBuffer,0,uSize); if(!IsRecordsetOpened()) return false; try { sql::SQLString tempstr = m_DBRecordSet->getString(columnLabel); strncpy(szBuffer,tempstr.c_str(),uSize-1); return true; } catch (sql::SQLException &e) { SetErrorInfo(e);} return false;}//获取参数bool CMySqlDataBase::GetFieldValue(const std::string& columnLabel,std::string &szValue){ if(!IsRecordsetOpened()) return false; try { szValue = m_DBRecordSet->getString(columnLabel).asStdString(); return true; } catch (sql::SQLException &e) { SetErrorInfo(e);} return false;}/*//获取参数,SYSTEMTIME 可以通过 COleDateTime(const SYSTEMTIME& systimeSrc) 转换为 COleDateTimebool CMySqlDataBase::GetFieldValue(const std::string& columnLabel,SYSTEMTIME &systime){ if(!IsRecordsetOpened()) return false; memset(&systime,0,sizeof(SYSTEMTIME)); try { std::string timestr = m_DBRecordSet->getString(columnLabel).asStdString(); sscanf(timestr.c_str(),"%04d-%02d-%02d %02d:%02d:%02d",&systime.wYear,&systime.wMonth,&systime.wDay, &systime.wHour,&systime.wMinute,&systime.wSecond); return true; } catch (sql::SQLException &e) { SetErrorInfo(e);} return false;}*/

 

检查内存增长测试的 leakcheck.h:

#pragma once#define CRTDBG_MAP_ALLOC#include 
#include
#include
#include
#include
#include
#pragma comment(lib,"psapi.lib")#ifdef _DEBUG#define malloc(s) _malloc_dbg(s, _NORMAL_BLOCK, __FILE__, __LINE__)#define calloc(c, s) _calloc_dbg(c, s, _NORMAL_BLOCK, __FILE__, __LINE__)#define realloc(p, s) _realloc_dbg(p, s, _NORMAL_BLOCK, __FILE__, __LINE__)#define new new(_NORMAL_BLOCK,__FILE__,__LINE__)#endif#define DEFAULT_OUT_TITLE \ TEXT("缺页中断数 工作集(KB) 虚存(KB) 虚存峰值(KB)")#define DEFAULT_OUTPUT_FORMAT \ TEXT(" %u %u %u %u ")// 字节单位转换,向0取整#define B2KB(x) ((x) >> 10)///void ConstructOutput(){ PROCESS_MEMORY_COUNTERS pmc; std::cout<
<

 

调用 test.cpp

#include "MySqlDataBase.h"#include "leakcheck.h"using namespace std;int main(){    CMySqlDataBase mysqldb;    try{        mysqldb.SetConnectionInfo("127.0.0.1",3306,"test","root","123456");        mysqldb.OpenConnect();        ConstructOutput();          //这个函数用来查看当前内存大小的        //for(int i = 0;i<100000;++i)        {            mysqldb.PreparedExcute("call testproc1(?)");            mysqldb.setInt(1,1001)            mysqldb.ExecuteCommand(true);            while(mysqldb.NextFieldExist())            {                int id;                std::string name;                mysqldb.GetFieldValue("id",id);                mysqldb.GetFieldValue("date",name);                cout<<"id:"<
<<", name:"<
<
getErrorCode()<<":"<
GetErrorDestribe()<

 

转载于:https://www.cnblogs.com/sixbeauty/p/4798228.html

你可能感兴趣的文章
Python学习笔记1:python简介、输入输出、循环条件
查看>>
python学习笔记5:装饰器
查看>>
Android 开发环境配置
查看>>
skiing
查看>>
wxwidgets demo
查看>>
dubbo 实战总结
查看>>
bzoj1230 [Usaco2008 Nov]lites 开关灯
查看>>
Modulation of Lipid Metabolism by Celastrol (文献分享一组-赵倩倩)
查看>>
HDU 1044 Collect More Jewels(BFS+DFS)
查看>>
TrackbarCallback 回调函数必须为 void(int,void*)
查看>>
【BZOJ1857】[Scoi2010]传送带 三分法
查看>>
得到相册里面的全部图片
查看>>
JPA与Spring2.5整合时发生不能创建entityManagerFactory的问题解决方法
查看>>
python 科学计算基础库安装
查看>>
vi/vim打开文件提示Found a swap file by the name
查看>>
jsp------实现MD5加密
查看>>
Double 和 Float的区别
查看>>
cygwin报错 /bin/bash: Operation not permitted
查看>>
洛谷P2617 Dynamic Rankings (主席树)
查看>>
编写可维护的JavaScript----笔记(二)
查看>>