zoukankan      html  css  js  c++  java
  • MySql循环插入大量数据,默认速度很慢的问题

    【转载自:http://www.jb51.net/article/52709.htm  -- 脚本之家,投稿:shichen2014】

    #  在针对大量数据的插入,更改等操作时,应该开启事务,待一连串的操作结束之后,再提交事务,可提高程序执行效率。

    通常来说C++操作MySQL的时候,往Mysql中插入10000条简单数据,速度非常缓慢,居然要5分钟左右,
    而打开事务的话,一秒不到就搞定了!

    具体实现代码如下:

    #include <iostream>
    #include <winsock2.h>
    #include <string>
     
    #include "mysql.h"
     
    #pragma comment(lib, "libmysql.lib");
     
    using namespace std;
     
    int main()
    {
     MYSQL mysql;
     mysql_init(&mysql); // 初始化
     
     MYSQL *ConnStatus = mysql_real_connect(&mysql,"localhost","root","","sky",3306,0,0);
     if (ConnStatus == NULL)
     {
     // 连接失败
     int i = mysql_errno(&mysql);
     string strError= mysql_error(&mysql);
     cout <<"Error info: "<<strError<<endl;
     
     return 0;
     }
     
     
     cout<<"Mysql Connected..."<<endl;
      
     string strsql;
     MYSQL_RES *result=NULL; // 数据结果集
     
     // 插入操作
     strsql = "insert into t1 values(2,'lyb')";
     
     mysql_query(&mysql,"START TRANSACTION"); // 开启事务, 如果没有开启事务,那么效率会变得非常低下!
     
     for (int i=0; i<10000; i++)
     {
     mysql_query(&mysql,strsql.c_str());
     }
     
     mysql_query(&mysql,"COMMIT");   // 提交事务
     
     cout<<"insert end"<<endl;
     
      
     //释放结果集 关闭数据库
     mysql_free_result(result);
     mysql_close(&mysql);
     mysql_library_end();
     
     return 0;
    }
  • 相关阅读:
    java学习day28-jQuery(常用)
    在博客园上添加bilibili视频
    参数传递 实参
    linux 下office软件推荐
    桥后总结 二
    go基础笔记-包
    Linux:Day24(上)
    Linux:Day23(下) vsftpd
    Linux:Day23(上) MariaDB SQL语句
    Linux:Day22(下) php及mysql使用基础
  • 原文地址:https://www.cnblogs.com/mybo/p/8183229.html
Copyright © 2011-2022 走看看