源原件test.cpp如下
#include <iostream>
#include "mysql/mysql.h"
#include <string.h>
using namespace std;
MYSQL _mysql;
static void do_stmt_sql(MYSQL *ms_conn)
{
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 atp_camp.FEISHU_ROBOT(url, type, remark) VALUES(?, ?, ?)";
int res = 0;
res = mysql_stmt_prepare(stmt, str_sql, sizeof(str_sql) - 1);
if (res != 0)
{
std::cout << "mysql_stmt_prepare INSERT failed."
<< mysql_stmt_error(stmt) << std::endl;
return ;
}
char szUrl[32];
memset(szUrl, 0x00, sizeof(szUrl));
sprintf(szUrl, "%s", "http://baidu.com");
char szRemark[32];
memset(szRemark, 0x00, sizeof(szRemark));
//sprintf(szRemark, "%s", "'");
sprintf(szRemark, "%s", "ha't'f''a'");
//sprintf(szRemark, "%s", "\\");
//sprintf(szRemark, "%s", "&");
int nType = 2;
MYSQL_BIND bind[3];
memset(bind, 0, sizeof(bind));
bind[0].buffer_type = MYSQL_TYPE_STRING;
//bind[0].is_null = NULL;
bind[0].buffer = szUrl;
bind[0].buffer_length = sizeof(szUrl);
bind[1].buffer_type = MYSQL_TYPE_LONG;
//bind[0].is_null = NULL;
bind[1].buffer = &nType;
//bind[1].buffer_length = sizeof(szUrl);
bind[2].buffer_type = MYSQL_TYPE_STRING;
//bind[0].is_null = NULL;
bind[2].buffer = szRemark;
bind[2].buffer_length = sizeof(szRemark);
res = mysql_stmt_bind_param(stmt, bind);
if (res != 0)
{
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_execute(stmt);
std::cout << "mysql_stmt_execute() func result is " << res << std::endl;
if (res)
{
fprintf(stderr, " %s\\n", mysql_stmt_error(stmt));
}
mysql_stmt_close(stmt), stmt = NULL;
}
int main()
{
mysql_thread_init();
mysql_init(&_mysql);
mysql_real_connect(&_mysql, "localhost", "用户", "密码",
"库名", 3306, NULL, 0);
if (0 != mysql_errno(&_mysql)) {
cout << "mysql connect failed" << endl;
return -1;
} else {
cout << "mysql connect success" << endl;
}
do_stmt_sql(&_mysql);
mysql_close(&_mysql);
return 0;
}
编译时需要连接mysql的库
makefile如下
test: test.cpp
g++ $^ -o $@ -lredis++ -lhiredis -lsqlite3 -pthread -L mysqlib/mysql/lib/ -lmysqlclient -std=c++11