Reputation: 185
I can't get the following code to work. It's working with normal select or insert, but when I try to insert a variable to it it didn't work. Can some let me know please what's wrong here?
Please note that the output is below.
int main(int argc, char **argv)
{
MYSQL *conn;
char str[100] = "test";
conn = mysql_init(NULL);
char stmt_buf[100];
sprintf (stmt_buf, "insert into test values ('%s')", str);
printf("\n%s\n",stmt_buf);
mysql_query (conn, stmt_buf);
mysql_close(conn);
return 0;
}
~$./version
insert into test values ('test')
Segmentation fault
Upvotes: 0
Views: 1536
Reputation: 57650
I didn't see you are connected to database by mysql_real_connect
also there is no mysql_select_db
and mysql_exec_sql
call.
Here is an example for you.
int main(int argc, char **argv)
{
MYSQL mysql;
char stmt_buf[100];
if (mysql_init(&mysql) == NULL) {
printf("Can not initialize");
exit(1);
}
if (!mysql_real_connect
(&mysql, "localhost", "USERNAME", "PASSWORD", NULL, 0, NULL, 0)) {
mysql_error(&mysql);
exit(1);
}
if (mysql_select_db(&mysql, "DATABASENAME")) {
mysql_error(&mysql);
exit(1);
}
sprintf(stmt_buf, "insert into test values ('%s')", "test");
if (mysql_exec_sql(&mysql, stmt_buf))
mysql_error(&mysql));
mysql_close(&mysql);
}
Upvotes: 1
Reputation: 213318
You don't do any error checking. My guess is conn == NULL
.
For the record, don't use sprintf
ever. Use snprintf
instead, that is, if you're okay with SQL injections.
Upvotes: 2