1. 程式人生 > >MySQL打包執行SQL

MySQL打包執行SQL

cat result disable tell roc 傳輸 兩個 pass 類型

當一次業務處理計算服務和數據庫交互較多時,將可能有大量時間浪費在數據傳輸上,尤其對於計算服務和數據庫跨機房或跨地區部署時,浪費的時間會極其可觀。為了減少時間浪費可以使用MySQL提供的SQL打包功能。

先來認識兩個標記:
CLIENT_MULTI_RESULTS:Tell the server that the client can handle multiple result sets from multiple-statement executions or stored procedures. This flag is automatically enabled if CLIENT_MULTI_STATEMENTS is enabled.

CLIENT_MULTI_STATEMENTS:Tell the server that the client may send multiple statements in a single string (separated by “;”). If this flag is not set, multiple-statement execution is disabled.

接下來通過一個例子了解如何使用MySQL這個功能:

新建表結構:

字段 類型 描述
id bigint(20) unsigned 自增ID,主鍵
trans_id varchar(32) 業務單據號,唯一索引
comments text 備註

主要代碼:

#include <stdio.h>
#include <string.h>
#include "mysql.h"

int main(int argc, const char* argv[])
{
    bool deal_ok = true;

    MYSQL* db_session = 0;

    // init db
    if (deal_ok)
    {
        db_session 
= mysql_init(db_session); if (0 != db_session) { printf("init db\n"); } else { deal_ok = false; printf(" init db error\n"); } } //connect db if (deal_ok) { char db_host[32] = {"127.0.0.1"}; char db_user[32] = {"test"}; char db_pass[32] = {"123456789"}; unsigned long db_port = 3306; unsigned long conn_flag = CLIENT_MULTI_STATEMENTS | CLIENT_REMEMBER_OPTIONS; if (mysql_real_connect(db_session, db_host, db_user, db_pass, 0, db_port, 0, conn_flag)) { printf("connect successed\n"); } else { deal_ok = false; printf("connect error: %s\n", mysql_error(db_session)); } } //start transaction if (deal_ok) { int db_ret = mysql_query(db_session, "START TRANSACTION"); if (0 == db_ret) { printf("start transaction\n"); } else { deal_ok = false; printf("start transaction error: %s\n", mysql_error(db_session)); } } //operate db if (deal_ok) { char db_sql[1024] = {0}; strcat(db_sql, "INSERT INTO test_db.test(trans_id, comments) VALUES(110, ‘test‘);"); strcat(db_sql, "UPDATE test_db.test SET comments = ‘modify‘ WHERE trans_id = ‘108‘;"); printf("operate db: %s\n", db_sql); int db_ret = mysql_real_query(db_session, db_sql, strlen(db_sql)); if (0 == db_ret) { while (0 == db_ret) {
          int affected_rows = (int)mysql_affected_rows(db_session);
          deal_ok = deal_ok && (0 < affected_rows);
printf(
" affected rows : %d\n", affected_rows); db_ret = mysql_next_result(db_session); } } else { deal_ok = false; printf("\terror: %s\n", mysql_error(db_session)); } } //complete transaction if (0 != db_session) { if (deal_ok) { mysql_commit(db_session); printf("commit\n"); } else { mysql_rollback(db_session); printf("rollback\n"); } mysql_close(db_session); } return 0; }

MySQL打包執行SQL