日期:2014-05-16  浏览次数:20788 次

linux c下向mysql服务器请求SQL语句的字符串构造问题
有char *sql;
char* sql2;
sql2 = "INSERT INTO appdata (name, time) VALUES ('new', 1)";
printf("%s,%d\n",sql,strlen(sql));
printf("%s,%d\n",sql2,strlen(sql2));
res = mysql_real_query(&mysql, sql, strlen(sql));
sql是一个用sprintf(sql, "INSERT INTO appdata (%s) VALUES (%s, %s)")创建出来的和sql2一模一样的字符串,sprintf打印的长度也相同,但是得到的输出结果却是

INSERT INTO appdata (name, time) VALUES ('new', 1),50
INSERT INTO appdata (name, time) VALUES ('new', 1),50
Insert error 1064: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''neq' at line 1

而把res = mysql_real_query(&mysql, sql, strlen(sql));的sql换成sql2,就能正常插入

如果把new换成neww,也能正常插入,这是什么原因?可能和字符集有关系,但是字符集已经用
mysql_set_character_set(&mysql, "utf8")
设置过了,大惑不解…



------解决方案--------------------
char *sql;
sprintf(sql, "INSERT INTO appdata (%s) VALUES (%s, %s)")


这个sql的空间怎么分配的? malloc?