解決 C++ 操作 MySQL 大量資料插入效率低下問題

來源:互聯網
上載者:User

標籤:action   操作   track   names   free   資料   tran   span   star   

往 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;}



總結:

在大量資料的插入,更改等操作時,應該開啟事務。等一連串的操作結束之後,再提交事務。可提高程式運行效率


解決 C++ 操作 MySQL 大量資料插入效率低下問題

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.