Reputation: 2087
I try to execute mysql query passing variable. Here is my code
char str[100] = "My String";
mysql_query(conn, printf("INSERT INTO table VALUES %s"), str);
I get that warning during compile process
warning: passing argument 2 of ‘mysql_query’ makes pointer from integer without a cast
What I miss ?
Upvotes: 1
Views: 7833
Reputation: 9740
You cannot do that. printf()
returns the number of characters printed. You have to create the string before calling mysql_query()
:
char statement[512], *my_str = "MyString";
snprintf(statement, 512, "INSERT INTO table VALUES ('%s')", str);
mysql_query(conn, statement);
Also, be careful when creating those query strings. Don't use functions like sprintf()
if you cannot be sure how long the resulting string is. Don't write over the boundaries of the memory segment.
Upvotes: 3
Reputation: 91017
Extending @ckruse's answer, you should take care to use mysql_real_escape_string()
if your string comes from arbitrary sources.
int insert_data(MYSQL * mysql, char * str, int len)
{
if (len < 0) {
len = strlen(str);
}
char esc[2*len+1];
unsigned long esclen = mysql_real_escape_string(mysql, esc, str, len);
char statement[512];
snprintf(statement, sizeof statement, "INSERT INTO table VALUES ('%s')", esc);
return mysql_query(mysql, statement);
}
(An alternative could be mysql_hex_string()
if dealt with correctly.)
Upvotes: 4
Reputation: 13315
you should put "'' in front and after the string like this
mysql_query(conn, printf("INSERT INTO table VALUES ('%s')"), str);
Upvotes: -1