MySQL打包执行SQL

时间:2022-06-24 18:27:54

当一次业务处理计算服务和数据库交互较多时,将可能有大量时间浪费在数据传输上,尤其对于计算服务和数据库跨机房或跨地区部署时,浪费的时间会极其可观。为了减少时间浪费可以使用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 = ; // init db
if (deal_ok)
{
db_session = mysql_init(db_session); if ( != db_session)
{
printf("init db\n");
}
else
{
deal_ok = false;
printf(" init db error\n");
}
} //connect db
if (deal_ok)
{
char db_host[] = {"127.0.0.1"};
char db_user[] = {"test"};
char db_pass[] = {""};
unsigned long db_port = ;
unsigned long conn_flag = CLIENT_MULTI_STATEMENTS | CLIENT_REMEMBER_OPTIONS; if (mysql_real_connect(db_session, db_host, db_user, db_pass, , db_port, , 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 ( == 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[] = {};
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 ( == db_ret)
{
while ( == 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 ( != 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 ;
}