当前位置:Gxlcms >
数据库问题 >
MYSQL C API : struct MYSQL_STMT 结构的组合使用
MYSQL C API : struct MYSQL_STMT 结构的组合使用
时间:2021-07-01 10:21:17
帮助过:34人阅读
#include <iostream>
2 #include <
string>
3
4 #include <
string.h>
5 #include <assert.h>
6
7 #include <mysql.h>
8
9 static void do_stmt_sql(MYSQL *
ms_conn);
10
11 int main()
12 {
13 // 初始化MYSQL 实例
14 MYSQL *ms_conn =
mysql_init(NULL);
15 if (ms_conn ==
NULL)
16 {
17 std::cout <<
"mysql init failed." <<
std::endl;
18 return 0;
19 }
20 std::cout <<
"mysql init successful." <<
std::endl;
21
22 // 连接到MYSQL 服务器
23 MYSQL *ms_ret = mysql_real_connect(ms_conn,
"localhost",
"suyh",
24 "suyunhong",
"suyh_db",
0, NULL,
0);
25 if (ms_ret ==
NULL)
26 {
27 std::cout <<
"mysql connect failed. "
28 << mysql_error(ms_conn) <<
std::endl;
29 mysql_close(ms_conn), ms_conn =
NULL;
30 return 0;
31 }
32 std::cout <<
"mysql connect successful." <<
std::endl;
33
34 do_stmt_sql(ms_conn);
35
36 // 释放资源
37 mysql_close(ms_conn), ms_conn =
NULL;
38 return 0;
39 }
40
41 static void do_stmt_sql(MYSQL *
ms_conn)
42 {
43 assert(ms_conn !=
NULL);
44 if (ms_conn ==
NULL)
45 return ;
46
47 MYSQL_STMT *stmt =
NULL;
48 stmt =
mysql_stmt_init(ms_conn);
49 if (stmt ==
NULL)
50 {
51 std::cout <<
"stmt is NULL. mysql_stmt_init failed. "
52 << mysql_error(ms_conn) <<
std::endl;
53 return ;
54 }
55 std::cout <<
"MYSQL_STMT init successful." <<
std::endl;
56
57 const char str_sql[] =
"INSERT INTO tb_bin_data(bin_data) VALUES(?)";
58
59 int res =
0;
60 res = mysql_stmt_prepare(stmt, str_sql,
sizeof(str_sql) -
1);
61 if (res !=
0)
62 {
63 std::cout <<
"mysql_stmt_prepare INSERT failed."
64 << mysql_stmt_error(stmt) <<
std::endl;
65 return ;
66 }
67
68 // 待存到MYSQL 的二进制数据
69 char bin_data[] = {
0,
1,
2,
3,
4,
5,
6,
7,
8,
9};
70
71 MYSQL_BIND bind[
1];
72 memset(bind,
0,
sizeof(bind));
73 bind[
0].buffer_type =
MYSQL_TYPE_BLOB;
74 bind[
0].is_null =
NULL;
75 bind[
0].buffer =
bin_data;
76 bind[
0].buffer_length =
sizeof(bin_data);
77
78 res =
mysql_stmt_bind_param(stmt, bind);
79 if (res !=
0)
80 {
81 std::cout <<
"mysql_stmt_bind_param failed. "
82 << mysql_stmt_error(stmt) <<
std::endl;
83 mysql_stmt_close(stmt), stmt =
NULL;
84 return ;
85 }
86 std::cout <<
"mysql_stmt_bind_param successful." <<
std::endl;
87
88 // res = mysql_stmt_send_long_data(stmt, 0, escape_bin, strlen(escape_bin));
89 // std::cout << "mysql_stmt_send_long_data result is " << res << std::endl;
90
91 res =
mysql_stmt_execute(stmt);
92 std::cout <<
"mysql_stmt_execute() func result is " << res <<
std::endl;
93
94 mysql_stmt_close(stmt), stmt =
NULL;
95 }
MYSQL C API : struct MYSQL_STMT 结构的组合使用
标签: