MySql C++调用库Connector/c++编译 和 接口封装【三】Connector/c++ 使用总结及封装

工程需要加上各个路径:

库使用需要几个文件:
  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 <map>

typedef boost::scoped_ptr<sql::Connection> Connection;
typedef boost::scoped_ptr<sql::PreparedStatement> PreparedStatement;
typedef boost::scoped_ptr<sql::Statement> Statement;
typedef boost::shared_ptr<sql::ResultSet> 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<std::string, std::string>    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 <sstream>

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://"<<hostIp<<":"<<hostPort;

        m_ConnectProperties["hostName"] = hostss.str();
        m_ConnectProperties["userName"] = userName;
        m_ConnectProperties["password"] = password;
        m_ConnectProperties["schema"] = dataBaseName;

        return true;
    }
    catch (sql::SQLException &e) { SetErrorInfo(e);}

    return false;
}

//是否打开
bool CMySqlDataBase::IsRecordsetOpened()
{
    if(m_DBRecordSet == NULL)
        return false; 

    if(m_DBRecordSet->isClosed())
        return false;

    return true;
}

//准备prepareState
bool 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 set
const ResultSet &CMySqlDataBase::GetRecordSet()
{
    return m_DBRecordSet;
}

//get Next Record set
bool CMySqlDataBase::GetNextResultSet()
{
    if(m_DBPrepareState == NULL)
        return false;

    if(m_DBPrepareState->getMoreResults())
    {
        m_DBRecordSet.reset(m_DBPrepareState->getResultSet());
        return true;
    }
    return false;
}

//next
bool 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) 转换为 COleDateTime
bool 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 <windows.h>
#include <tchar.h>
#include <crtdbg.h>
#include <stdlib.h>
#include <iostream>
#include <Psapi.h>
#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<<DEFAULT_OUT_TITLE<<std::endl;
    if(!GetProcessMemoryInfo(GetCurrentProcess(),&pmc,sizeof(pmc)))return ;

    char output[512] = {0};
    _sntprintf(output,sizeof(output),DEFAULT_OUTPUT_FORMAT,
        (pmc.PageFaultCount),B2KB(pmc.WorkingSetSize),B2KB(pmc.PagefileUsage),B2KB(pmc.PeakPagefileUsage));
    std::cout<<output<<std::endl;
}

调用 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:"<<id<<", name:"<<name<<endl;
            }
        }
        ConstructOutput();
        mysqldb.CloseConnect();
    }
    catch(CMySqlError *pSqlError)
    {
        cout<<pSqlError->getErrorCode()<<":"<<pSqlError->GetErrorDestribe()<<endl;
        mysqldb.CloseConnect();
    }

    return 0;
}
原文地址:https://www.cnblogs.com/sixbeauty/p/4798228.html