当一次业务处理计算服务和数据库交互较多时,将可能有大量时间浪费在数据传输上,尤其对于计算服务和数据库跨机房或跨地区部署时,浪费的时间会极其可观。为了减少时间浪费可以使用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) { printf(" affected rows : %d\n", (int)mysql_affected_rows(db_session)); 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; }