Title:Linux C 调用MYSQL API 函数mysql_escape_string()转义插入数据 --2013-10-11 11:57
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "mysql.h" int main(int argc, char *argv[])
{
MYSQL my_connection;
int res;
mysql_init(&my_connection);
char UNAMES[50];
char sql_insert[400];
char *p[5];
p[0]="123456";
p[1]="Fuc'a'k";
p[2]="127.0.0.1";
p[3]="2013-09-26 10:10:10";
p[4]="1"; /*mysql_real_connect(&mysql,host,user,passwd,dbname,0,NULL,0) == NULL)*/
if (mysql_real_connect(&my_connection, "127.0.0.1", "root", "FuckFuck","databasename",0,NULL,CLIENT_FOUND_ROWS))
{
printf("Connection success\n");
mysql_escape_string(UNAMES,p[1],strlen(p[1]));
snprintf(sql_insert, sizeof(sql_insert),"insert into `tablename` (`C1`,`C2`,`C3`,`C4`,`C5`) values ('%s','%s','%s','%s','%s');",p[0],UNAMES,p[2],p[3],p[4]);
res = mysql_query(&my_connection,sql_insert); if (!res)
{
printf("Inserted %lu rows\n",(unsigned long)mysql_affected_rows(&my_connection));
printf("%s------\n",sql_insert);
printf("%s------\n",UNAMES);
/*里头的函数返回受表中影响的行数*/
}
else
{
//分别打印出错误代码及详细信息
fprintf(stderr, "Insert error %d: %s\n",mysql_errno(&my_connection),mysql_error(&my_connection));
}
mysql_close(&my_connection);
} else
{
fprintf(stderr, "Connection failed \n"); if (mysql_errno(&my_connection))
{
fprintf(stderr, "Connection error %d: %s\n",mysql_errno(&my_connection),mysql_error(&my_connection));
}
}
return EXIT_SUCCESS;
}