Insert client input into MySQL database with C
How do I write a C program which gets the client input for MySQL server? I'm using Fedora as my OS.
Here is my code:
#include<my_global.h>
#include<mysql.开发者_Go百科h>
main()
{
char name[25];
MYSQL *conn;
conn=mysql_init(NULL);
mysql_real_connect(conn,"localhost","root","","testdb",0,NULL,0);
printf("Enter your name:");
scanf("%s",name);
mysql_query(conn,"CREATE TABLE Users(name VARCHAR(25))");
mysql_query(conn,"INSERT INTO Users VALUES(name)");
//mysql_query(conn,"INSERT INTO Users VALUES('Farhan')");
//mysql_query(conn,"INSERT INTO Users VALUES('Dileep')");
//mysql_query(conn,"INSERT INTO Users VALUES('RAJIV')");
mysql_close(conn);
}
I want the client input to be stored in MySQL database and not the constant values.
Try sprintf'ing the name into your query, something like this:
int len = query_len + name_len + 1;
char * insert_query = (char *) malloc(len);
snprintf(insert_query, len, "INSERT INTO Users VALUES('%s')", name);
However, you'll need to take some care when checking the buffer lengths and especially escaping the name string.
精彩评论