MYSQL C API : struct MYSQL_STMT 结构的组合使用

 #include <iostream>
#include <string> #include <string.h>
#include <assert.h> #include <mysql.h> static void do_stmt_sql(MYSQL *ms_conn); int main()
{
// 初始化MYSQL 实例
MYSQL *ms_conn = mysql_init(NULL);
if (ms_conn == NULL)
{
std::cout << "mysql init failed." << std::endl;
return ;
}
std::cout << "mysql init successful." << std::endl; // 连接到MYSQL 服务器
MYSQL *ms_ret = mysql_real_connect(ms_conn, "localhost", "suyh",
"suyunhong", "suyh_db", , NULL, );
if (ms_ret == NULL)
{
std::cout << "mysql connect failed. "
<< mysql_error(ms_conn) << std::endl;
mysql_close(ms_conn), ms_conn = NULL;
return ;
}
std::cout << "mysql connect successful." << std::endl; do_stmt_sql(ms_conn); // 释放资源
mysql_close(ms_conn), ms_conn = NULL;
return ;
} static void do_stmt_sql(MYSQL *ms_conn)
{
assert(ms_conn != NULL);
if (ms_conn == NULL)
return ; MYSQL_STMT *stmt = NULL;
stmt = mysql_stmt_init(ms_conn);
if (stmt == NULL)
{
std::cout << "stmt is NULL. mysql_stmt_init failed. "
<< mysql_error(ms_conn) << std::endl;
return ;
}
std::cout << "MYSQL_STMT init successful." << std::endl; const char str_sql[] = "INSERT INTO tb_bin_data(bin_data) VALUES(?)"; int res = ;
res = mysql_stmt_prepare(stmt, str_sql, sizeof(str_sql) - );
if (res != )
{
std::cout << "mysql_stmt_prepare INSERT failed."
<< mysql_stmt_error(stmt) << std::endl;
return ;
} // 待存到MYSQL 的二进制数据
char bin_data[] = {, , , , , , , , , }; MYSQL_BIND bind[];
memset(bind, , sizeof(bind));
bind[].buffer_type = MYSQL_TYPE_BLOB;
bind[].is_null = NULL;
bind[].buffer = bin_data;
bind[].buffer_length = sizeof(bin_data); res = mysql_stmt_bind_param(stmt, bind);
if (res != )
{
std::cout << "mysql_stmt_bind_param failed. "
<< mysql_stmt_error(stmt) << std::endl;
mysql_stmt_close(stmt), stmt = NULL;
return ;
}
std::cout << "mysql_stmt_bind_param successful." << std::endl; // res = mysql_stmt_send_long_data(stmt, 0, escape_bin, strlen(escape_bin));
// std::cout << "mysql_stmt_send_long_data result is " << res << std::endl; res = mysql_stmt_execute(stmt);
std::cout << "mysql_stmt_execute() func result is " << res << std::endl; mysql_stmt_close(stmt), stmt = NULL;
}
上一篇:sFlow-RT


下一篇:CF 1083 B. The Fair Nut and Strings