tags:

views:

81

answers:

3

I have been working with the tutorial on MySQL C API from http://zetcode.com/tutorials/mysqlcapitutorial/ the following example is working fine:

#include <my_global.h>
#include <mysql.h>

int main(int argc, char **argv)
{

MYSQL *conn;

conn = mysql_init(NULL);
mysql_real_connect(conn, "localhost", "zetcode", "passwd", "testdb", 0, NULL, 0);

mysql_query(conn, "CREATE TABLE writers(name VARCHAR(25))");

mysql_query(conn, "INSERT INTO writers VALUES('Leo Tolstoy')");
mysql_query(conn, "INSERT INTO writers VALUES('Jack London')");
mysql_query(conn, "INSERT INTO writers VALUES('Honore de Balzac')");
mysql_query(conn, "INSERT INTO writers VALUES('Lion Feuchtwanger')");
mysql_query(conn, "INSERT INTO writers VALUES('Emile Zola')");

mysql_close(conn);

}

How can i change the code to accept custom values instead of the hardcoded ones, is it possible to replace writers and ex. Leo Tolstoy with a char pointer or something?

A: 

You will likely have to compose your strings, e.g. using sprintf().

Svante
+1  A: 

You can probably use sprintf() / snprintf(), as for example:

#include <my_global.h>
#include <mysql.h>

int main(int argc, char **argv)
{
MYSQL *conn;
conn = mysql_init(NULL);
/* error checking missing */
mysql_real_connect(conn, "localhost", "zetcode", "passwd", "testdb", 0, NULL, 0);
/* error checking missing */
mysql_query(conn, "CREATE TABLE writers(name VARCHAR(25))");
/* error checking missing */
do {
    char cmd[1000];
    char *name = "Leo Tolstoy"; /* get from user or file or something */
    snprintf(cmd, 999, "INSERT INTO writers VALUES('%s')", name);
    /* error checking missing */
    mysql_query(conn, cmd);
    /* error checking missing */
} while (0);
mysql_close(conn);
/* error checking missing */
}
pmg
+2  A: 

You have basically two options:

Lukáš Lalinský
Regarding escaping strings, this only applies to user-supplied values. You should take care to differentiate between safe and unsafe data.
Svante
Well, there are no "safe" data. Either you have variables that come from files, user input, etc. or you have constants in your code. Even with constants, I'd rather let the MySQL client to do the escaping, because it knows better than me what to escape.
Lukáš Lalinský