#include <stdio.h>
#include <stdlib.h>
#include <mysql.h>
/* 1 id 2 type(1->tcp 2->UDP) 3 src_ip 4 dst_ip 5 src_port 6 dst_port 7 content 8 seq
gcc -o inputMysqlTest1.o $(mysql_config --cflags) inputMysqlTest1.c $(mysql_config --libs)
*/
int main(int argc, char** argv)
{
MYSQL *my_conn;
my_conn=mysql_init(NULL);
int res=0;
if(!mysql_real_connect(my_conn,"localhost","root","","MyTest1",0,NULL,0)) //连接test数据库
{
printf("Connect Error!n");
exit(1);
}
res = mysql_query(my_conn,"INSERT INTO netDataTest(type, src_ip, dst_ip, src_port, dst_port, content, seq) VALUES(1, '10.1.2.3', '192.168.1.101' , 80, 7000, 'hehe', 22 ) ");
if (!res)
{
printf("Inserted %lu rows\n", (unsigned long)mysql_affected_rows(my_conn));
}
else
{
fprintf(stderr, "Insert error %d: %s\n", mysql_errno(my_conn),
mysql_error(my_conn));
}
mysql_close(my_conn);
return 0;
}
如果要插入变量,就稍微复杂点。需要将sql语句复制到string里面(注意‘和“的使用)。
变量只能是字符串型,所以需要将int转为string. 这里用到的是std::stringstream。
stream << id;
string sid=stream.str();
不要忘了清空缓存,stream.str("");
#include <stdio.h>
#include <stdlib.h>
#include <mysql.h>
#include <string>
#include <sstream>
using namespace std;
/* 1 id 2 type(1->tcp 2->UDP) 3 src_ip 4 dst_ip 5 src_port 6 dst_port 7 content 8 seq
g++ -o inputMysqlTest2.o $(mysql_config --cflags) inputMysqlTest2.cpp $(mysql_config --libs)
*/
int main(int argc, char** argv)
{
MYSQL *my_conn;
my_conn=mysql_init(NULL);
int res=0;
if(!mysql_real_connect(my_conn,"localhost","root","","MyTest1",0,NULL,0)) //连接test数据库
{
printf("Connect Error!n");
exit(1);
}
int id =29;int type=1;
string content = "ajsdaksdjsadaskdkasddaw";
string src_ip = "10.1.2.3";
string dst_ip = "100.12.2.322";
int src_port=80;
int dst_port=7077;
int seq = 98233;
std::stringstream stream;
string sid, stype,ssrc_port,sdst_port,sseq;
stream << id;
sid=stream.str();
stream.str("");
stream << type;
stype=stream.str();
stream.str("");
stream << src_port;
ssrc_port=stream.str();
stream.str("");
stream << dst_port;
sdst_port=stream.str();
stream.str("");
stream << seq;
sseq=stream.str();
stream.str("");
string str ="INSERT INTO netDataTest VALUES( NULL, '"+ stype +"', '"+ src_ip +"', '"+ dst_ip +"', '"+ ssrc_port +"', '"+ sdst_port +"', '"+ content +"', '"+ sseq +"');";
//res = mysql_query(my_conn, str.c_str());
res =mysql_real_query( my_conn , str.c_str() , str.length() );
if (!res)
{
printf("Inserted %lu rows\n", (unsigned long)mysql_affected_rows(my_conn));
}
else
{
fprintf(stderr, "Insert error %d: %s\n", mysql_errno(my_conn),
mysql_error(my_conn));
}
mysql_close(my_conn);
return 0;
}