C API 连接MySQL及批量插入

时间:2021-02-11 21:47:17

CMySQLMgr.h:

#ifndef _CMYSQLMGR_H_
#define _CMYSQLMGR_H_ #include <iostream>
#include "mysql.h" using namespace std; class CMySQLMgr
{
public:
CMySQLMgr();
~CMySQLMgr(); bool Connect(const char * sHost, const char * sUser, const char * sPwd, const char * sDbName, const char * sPort);
void CloseConnect(); bool excute(const char * sQuery); MYSQL * GetpMysql(); private:
MYSQL * m_pMysql;
}; #endif

  

CMySQLMgr.cpp:

#include "CMySQLMgr.h"

CMySQLMgr::CMySQLMgr()
{
m_pMysql = NULL;
} CMySQLMgr::~CMySQLMgr()
{ } bool CMySQLMgr::Connect( const char * sHost, const char * sUser, const char * sPwd, const char * sDbName, const char * sPort )
{
bool bReturn = true;
do
{
CloseConnect();
m_pMysql = mysql_init(NULL);
if (!m_pMysql)
{
bReturn = false;
//can write log
break;
} //参数设置
char optvalue = 6;
mysql_options(m_pMysql, MYSQL_OPT_CONNECT_TIMEOUT, (char*)&optvalue);
optvalue = 1;
mysql_options(m_pMysql, MYSQL_OPT_RECONNECT, (char*)&optvalue);
optvalue = 2;
mysql_options(m_pMysql, MYSQL_OPT_READ_TIMEOUT, (char*)&optvalue); if (!mysql_real_connect(m_pMysql, sHost, sUser, sPwd, sDbName, atoi(sPort), NULL, 0) )
{
bReturn = false;
//can write log
cout << "mysql error:" << mysql_error(m_pMysql);
break;
}
} while (0); return bReturn;
} void CMySQLMgr::CloseConnect()
{
if (m_pMysql)
{
mysql_close(m_pMysql);
}
} bool CMySQLMgr::excute( const char * sQuery )
{
bool bReturn = true;
try
{
if (0 != mysql_query(m_pMysql, sQuery))
{
bReturn = false;
cout << "mysql error:" << mysql_error(m_pMysql);
//can write log
}
}
catch (std::exception &e)
{
cout << "exception:" << e.what() << endl;
}
catch (...)
{
cout << "Unknown exception." << endl;
} return bReturn;
} MYSQL * CMySQLMgr::GetpMysql()
{
if (m_pMysql)
{
return m_pMysql;
}
}

main.cpp:

#include <iostream>
#include <stdio.h>
#include "CMySQLMgr.h"
using namespace std; int main()
{
CMySQLMgr mysql;
bool bRet = mysql.Connect("172.16.8.110", "root", "123456", "scistock", "3306"); char buf[1024*2] = {0}; const char * sSql = "select * from calcgsdataflash where gscode = 'ZTJB' ";
bRet = mysql.excute(sSql);
if (!bRet)
{
cout << "sSql:" << sSql << " excute error" << endl;
} MYSQL_RES *res;
MYSQL_ROW row;
MYSQL_FIELD *fields;
res = mysql_store_result(mysql.GetpMysql());
if (res)
{
int nFields = mysql_num_fields(res);
fields = mysql_fetch_fields(res); while ((row = mysql_fetch_row(res)))
{
string gpcode;
int ymd = 0;
int hms = 0;
float f10 = 0;
for (int j = 0; j < nFields; j++)
{
if (row[j])
{
if (strncmp(fields[j].name, "gpcode", strlen("gpcode")) == 0)
{
gpcode = row[j];
}
else if (strncmp(fields[j].name, "ymd", strlen("ymd")) == 0)
{
ymd = atoi(row[j]);
}
else if (strncmp(fields[j].name, "hms", strlen("hms")) == 0)
{
hms = atoi(row[j]);
int hour = hms / 3600;
int minute = hms / 60 % 60;
int second = hms % 60;
hms = hour * 10000 + minute * 100 + second;
}
else if (strncmp(fields[j].name, "f10", strlen("f10")) == 0)
{
f10 = atoi(row[j]);
}
}
} sprintf(buf, "update calcgsdataflash set hms = %d WHERE gscode = 'ZTJB' AND ymd = %d AND gpcode = '%s' AND f10 = %f", hms, ymd, gpcode.c_str(), f10);
cout << "sSql:" << buf << endl;
bool bRet = mysql.excute(buf);
if (!bRet)
{
cout << "sSql:" << buf << " excute error" << endl;
}
}
mysql_free_result(res);
}
mysql.CloseConnect();
return 0;
}

 

MySQL官网(https://www.mysql.com/

Api 连接库下载地址(https://dev.mysql.com/downloads/connector/c/

Windows :

  1.从官网下载Windows的对应版本的连接库。

    C API 连接MySQL及批量插入

  2.解压 1 中下载的压缩包

     C API 连接MySQL及批量插入

  3.vs 项目中加入 2 中库文件目录下的 include文件夹、lib文件夹下的 libmysql.lib。

    (将 libmysql.dll 拷贝至可执行程序目录下)

    项目配置(Debug or Release、Win32 or x64)要与下载的库版本保持一致。

    若 Release 模式下需要断点调试,参见:http://www.cnblogs.com/SZxiaochun/p/6928854.html

    C API 连接MySQL及批量插入

Linux:

  1.从官网下载 Linux 对应版本的连接库

    C API 连接MySQL及批量插入

  2.安装库

    1.如果下载的是压缩包

      C API 连接MySQL及批量插入

      解压之后

        sudo cp -r include/ /usr/include/mysql/

        sudo cp -r lib/ /usr/lib64/mysql/

    2.如果下载的是 .rpm 文件,直接安装

        sudo rpm -ivh mysql-connector-c-devel-6.1.11-1.el7.x86_64.rpm (rpm 命令的用法参见:http://www.cnblogs.com/SZxiaochun/p/7718606.html

    3.makefile 引用安装的库

      1.静态库 libmysqlclient.a

         C API 连接MySQL及批量插入

      2.动态库 libmysqlclient.so (如果安装之后没有 libmysqlclient.so ,只有 libmysqlclient.so.18.0.0,就链接一下 ln libmysqlclient.so.18.0.0 libmysqlclient.so ,或者重命名也行)

         C API 连接MySQL及批量插入

批量插入:

//InnoDB表引擎下关闭mysql自动事务提交可以大大提高数据插入的效率,这是因为如果需要插入1000条数据,    mysql会自动发起(提交)1000次的数据写入请求,如果把autocommit关闭掉,通过程序来控制,只要一 次commit就可以搞定。

#define WRITE_ONCE_COUNT  1000  //设一个宏,表示多少条数据提交一次

int count = 0;            //设一个计数值

mysql_autocommit(mysql,0);//关闭自动提交

sprintf(buf,"insert into dxjl_infobase(Date,gpcode,Type) values(%d,'%s',%d)",nDate,codes,1);

ASC2UTF8(buf,buf,sizeof(buf));//转编码,将ASC转为UTF8  以便数据库可以识别sql语句

int iSuccess = mysql_query(mysql,buf);
if(iSuccess !=0)
{
printf("mysql_query:%s\r\n",mysql_error(mysql));
}
else
{
count ++;
}
if(WRITE_ONCE_COUNT == count)//每WRITE_ONCE_COUNT条数据提交一次
{
mysql_commit(mysql);
count = 0;
}
出了循环之后加个判断,避免最后一次循环数据未达到WRITE_ONCE_COUNT,无法commit提交写库:
if(0 < count)
{
mysql_commit(mysql);
}

autocommit是事务,==1时是立即提交,==0之后遇到commit或rollback才提交。