#include <iostream>
#include <string>
#include <string.h>
#include <mysql.h>
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", "root",
"123456sx", "temp", , NULL, );
if (ms_ret == NULL)
{
std::cout << "mysql connect failed." << std::endl;
std::cout << mysql_error(ms_conn) << std::endl;
mysql_close(ms_conn), ms_conn = NULL;
return ;
}
std::cout << "mysql connect successful." << std::endl;
// 待存到MYSQL 的二进制数据
char bin_data[] = {, , , , , , , , , };
// 转义二进制数为一条字符串数据,
// 同时mysql_real_escape_string() 生成的字符串会自动添加尾零
char *escape_bin = new char[sizeof(bin_data) * + ];
mysql_real_escape_string(ms_conn,
escape_bin, bin_data, sizeof(bin_data));
// 生成SQL 语句
std::string str_sql = "";
str_sql += "INSERT INTO tb_bin_data(bin_data) VALUES('";
str_sql += escape_bin;
str_sql += "')";
delete [] escape_bin, escape_bin = NULL;
int res = ;
res = mysql_real_query(ms_conn, str_sql.c_str(),
str_sql.size());
if (res != )
{
std::cout << "Error: query failed. "
<< mysql_error(ms_conn) << std::endl;
}
else
{
std::cout << "Info: query successful." << std::endl;
}
// 释放资源
mysql_close(ms_conn), ms_conn = NULL;
return ;
}