0

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?

3 Answers 3

3

You have basically two options:

Sign up to request clarification or add additional context in comments.

2 Comments

Regarding escaping strings, this only applies to user-supplied values. You should take care to differentiate between safe and unsafe data.
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.
0

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

Comments

0

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 */
}

1 Comment

Might i add if your going to do it this way and get the input from ... well ... anywhere, your going to want to mysql_real_escape_string all of your variable to make sure that you don't fall victim to a SQL injection attack as stated by @Lukáš Lalinský link

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.