c mysql 批量存储_C API向MySQL插入批量数据的快速方法——关于mysql_autocommit

intH_Utility::insertRecordsToMySQL(const char*dataFilePath,const char*host,const char*user,const char*password,const char*schema,const char*table,const intport,const char*logFilePath)

{

ifstream rpf;

rpf.open(dataFilePath);int lineCount = 0;if(rpf.is_open())

{

MYSQL mysql;

mysql_init(&mysql);if(!mysql_real_connect(&mysql, host, user, password, schema, port, NULL, 0))

{

printf("MySQL数据库连接失败。\n");return -1;

}

ofstream f1(logFilePath);if (!f1.is_open())

{

printf("日志文件创建失败!\n");return 0;

}

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

char* out_text = new char[1024];int cursor = 0;while (!rpf.eof())

{

memset(out_text,0x00,1024);

rpf.getline(out_text,1024);stringstr(out_text);if (str.length()>0)

{

lineCount++;if (lineCount>1)

{

std::vectorstrVec;int cellCount = H_Utility::stringSplitToVector(str.c_str(), strVec, ",");if (cellCount<3)

{

printf("第%d行数据不完整,写入失败:\n",lineCount);

f1<

}string sql_str = "";

sql_str.append("INSERT INTO `").append(SCHEMA_NAME).append("`.`").append(TABLE_NAME).append("`");

sql_str.append("(id,name,birthday) values (");

sql_str.append(strVec[0]).append(",'").append(strVec[1]).append("',");

sql_str.append("STR_TO_DATE('").append(strVec[31]).append("','%Y-%m-%d %H:%i:%s'))");int iSuccess = mysql_query(&mysql, sql_str.c_str());if (iSuccess != 0)

{const char *mysql_err = mysql_error(&mysql);

printf("%s\n",mysql_err);

f1<

}else{

cursor++;

}if (cursor==50000)//每50000条记录提交一次

{

mysql_commit(&mysql);

cursor= 0;

printf("%d\n",lineCount);

}

}

}

}

delete []out_text;

rpf.close();

f1.flush();

f1.close();

mysql_close(&mysql);

}returnlineCount;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值