MYSQL C API : CLIENT_MULTI_STATEMENTS 选项

时间:2023-11-15 23:33:38
 #include <iostream>
#include <mysql.h>
#include <string> #include <assert.h> int main()
{
MYSQL *ms_conn = mysql_init(NULL);
if (ms_conn == NULL)
{
std::cout << "Error: mysql_init failed." << std::endl;
return ;
}
std::cout << "Info: mysql_init success." << std::endl; // 参数CLIENT_MULTI_STATEMENTS 指定一次query 可以执行多条SQL
MYSQL *ms_temp = NULL;
ms_temp = mysql_real_connect(ms_conn, "localhost", "root", "123456sx",
"suyh", , NULL, CLIENT_MULTI_STATEMENTS);
if (ms_temp == NULL)
{
std::cout << "Error: mysql_real_connect() failed." << std::endl;
std::cout << mysql_error(ms_conn) << std::endl;
mysql_close(ms_conn), ms_conn = NULL;
return ;
}
std::cout << "Info: mysql_real_connect() succect." << std::endl; std::string str_sqls = "";
str_sqls += "SELECT id, account, sex, level, powers FROM player_data WHERE id = 100000";
str_sqls += ";";
str_sqls += "SELECT id, account, sex, level, powers FROM player_data WHERE id = 100001";
str_sqls += ";";
str_sqls += "SELECT id, account, sex, level, powers FROM player_data WHERE id = 100002"; int res = ;
res = mysql_real_query(ms_conn, str_sqls.c_str(), str_sqls.size());
if (res != )
{
std::cout << "Info: query failed, sql: " << str_sqls.c_str() << std::endl;
std::cout << mysql_error(ms_conn) << std::endl;
}
else
{
std::cout << "Info: query success." << std::endl;
std::cout << std::endl; // CLIENT_MULTI_STATEMENTS 指定该选项需要mysql_next_result() 函数来获取下一条结果集
// 如果结果集未取完,则不能进行query 操作。
do
{
MYSQL_RES *ms_res = mysql_store_result(ms_conn);
assert(ms_res != NULL); unsigned int field_num = mysql_num_fields(ms_res);
std::cout << "fileds number is " << field_num << std::endl; MYSQL_FIELD* field_info = mysql_fetch_field(ms_res);
assert(field_info != NULL); MYSQL_ROW row_data = NULL;
while ()
{
row_data = mysql_fetch_row(ms_res);
if (row_data == NULL)
break; unsigned long *field_lens = mysql_fetch_lengths(ms_res);
assert(field_lens != NULL);
for (int i = ; i < field_num; ++i)
{
if (field_info[i].type == MYSQL_TYPE_BLOB)
{
std::cout << "current filed type is BLOB." << std::endl;
continue;
} if (row_data[i] == NULL)
{
std::cout << "field_lens[" << i << "] = " << field_lens[i]
<< ", value is NULL." << std::endl;
}
else
{
std::cout << "field_lens[" << i << "] = " << field_lens[i]
<< ", value is " << row_data[i] << std::endl;
}
}
} mysql_free_result(ms_res), ms_res = NULL; std::cout << "#######################################" << std::endl;
} while (mysql_next_result(ms_conn) == );
} mysql_close(ms_conn), ms_conn = NULL;
return ;
}