我得到了以下sql_buildup_method ...代码有点脏,但事实并非如此
char *build_up_sql(char *inputName,char *inputMessage)
{
char firstPartStatement[1064] ="INSERT INTO User (name, msg) VALUES (";
char *endPartStatement =");";
char *lightener = "'";
char *statement;
strcat(firstPartStatement,lightener);
strcat(firstPartStatement,inputName);
strcat(firstPartStatement,lightener);
strcat(firstPartStatement,",");
strcat(firstPartStatement,lightener);
strcat(firstPartStatement,inputMessage);
strcat(firstPartStatement,lightener);
strcat(firstPartStatement,endPartStatement);
statement = firstPartStatement;
return statement;
}
void create_input(sqlite3 *handler,char *inputName,char *inputMessage)
{
char *sql;
sql = build_up_sql(inputName,inputMessage);
// sql ="INSERT INTO User (name, msg) VALUES ('Susanne','hi all');";
printf("%s\n",sql);
sqlite3_exec(handler,sql, NULL, NULL, NULL);
}
printf给出输出:INSERT INTO User(name,msg)VALUES('Susanne','hi all');这是完全没问题...但是sqlite3_exec忽略它并且没有生成新的数据库输入....如果我离开行 sql =“INSERT INTO用户(名称,消息)VALUES('Susanne','嗨所有');“; 在代码中sqlite3_exec工作得很好....也把所有东西放在一个函数中也解决了问题,但这不应该是一个选项.....
答案 0 :(得分:1)
这里的问题是你返回一个指向局部变量的指针,这是未定义的行为。当build_up_sql
返回时,将重用堆栈中用于局部变量的空间。
最好的解决方案可能是添加一个用于放置字符串的build_up_sql
的参数。例如:
char *build_up_sql(char *inputName, char *inputMessage, char *outputSql)
{
const char firstPartStatement[] = "INSERT INTO User (name, msg) VALUES (";
const char endPartStatement[] = ");";
const char lightener[] = "'";
strcpy(outputSql, firstPartStatement);
strcat(outputSql,lightener);
strcat(outputSql,inputName);
strcat(outputSql,lightener);
strcat(outputSql,",");
strcat(outputSql,lightener);
strcat(outputSql,inputMessage);
strcat(outputSql,lightener);
strcat(outputSql,endPartStatement);
return outputSql;
}
void create_input(sqlite3 *handler, char *inputName, char *inputMessage)
{
char sql[1024];
char *sqlstr = build_up_sql(inputName, inputMessage, sql);
printf("%s\n", sqlstr);
sqlite3_exec(handler, sqlstr, NULL, NULL, NULL);
}