我在R中使用MySQL查询在数据库中插入数据,另外还使用字符串变量在数据库中插入数据。
我得到这个错误:
格式不是字符串文字且没有格式参数[-Wformat-security]
这是密码

void add_data_to_the_table(MYSQL * connection){
    char schlName[200]={};
    printf("Enter the school name  \n");
    scanf("%s",schlName);
    char query_string[] = { "INSERT INTO schools(schoolName) VALUES(%s)" };
    sprintf(schlName, query_string);
    if (mysql_query(connection,buf))
    {
     validate(connection);
    }
}

我本来希望将字符串插入数据库中的表schools中,但是我得到了上面的错误。

最佳答案

对于初学者来说,数组的初始化

char schlName[200]={};

在C中不正确。大括号中的初始值设定项列表不能为空。改为写
char schlName[200]={ '\0' };

在sprintf调用中,参数的顺序无效。你好像是说
sprintf( result_string, query_string, schlName );

而不是
sprintf( schlName, query_string);

其中result_string是将重定向输出的字符串。
函数sprintf的声明如下
int sprintf(char * restrict s, const char * restrict format, ...);

因此,如果与参数格式对应的参数具有类似于%s的转换说明符,则至少需要提供三个参数。
注意这个电话
scanf("%s",schlName);

是不安全的。使用fgets而不是scanf

关于c - 调用sprintf函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58216687/

10-11 23:17
查看更多