c - sqlite3_exec函数忽略sql构建函数值

标签 c

我得到了以下 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 User (name, msg) VALUES ('Susanne','大家好');"; 在代码中 sqlite3_exec 工作正常......还将所有内容放在一个函数中也解决了问题,但这不应该是一种选择......

最佳答案

这里的问题是您返回一个指向局部变量的指针,这是未定义的行为。当 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);
}

关于c - sqlite3_exec函数忽略sql构建函数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11537658/

相关文章:

c++ - XORing "Hello World!"切断字符串

C 编程,我输入名称,然后通过 for 循环,它将显示

c - 递归释放二叉树时出现段错误

c - 读取文件并将输入转换为两个数组

c - c 中的二维数组排序

c - 弹出 x86 堆栈以访问函数 arg 时出现段错误

c - 如果使用不正确的格式说明符打印存储在字符变量中的值,printf() 返回什么?

c++ - 如何将数组指向嵌入式系统上的某个特定内存地址

c++ - 我怎么知道我正在使用什么操作系统?

c++ - 在数组中获取和存储内存地址的问题