c++ and MYSQL

Sep 23, 2009 at 7:33pm
Im trying to write a c++ program that inputs variables into the database its not working out so well.
I can input into the database but cant seem to input variables. Any help would be greatly appreciated this is what I have so far.

The variable is "input"

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
   MYSQL mysql;
   MYSQL_ROW row;
   MYSQL_RES *result;

   unsigned int num_fields;
   unsigned int i;
   mysql_init(&mysql);

   if (!mysql_real_connect(&mysql,"localhost","root","something","tablename",0,NULL,0))
   {
      fprintf(stderr, "Failed to connect to database: Error: %s\n",
           mysql_error(&mysql));
   }
   else {
    if(mysql_query(&mysql, "INSERT INTO list VALUES ('',input.c_str(),'testpassword')"));
         //here goes the error message :o)
   }

   return 0;


Input is a variable string and in this format nothing happens nothing gets input to the db.

and if i do this

if(mysql_query(&mysql, "INSERT INTO list VALUES ('','input.c_str()','testpassword')"));

then input.c_str() is input into the db not the string inside input.
Sep 23, 2009 at 8:55pm
"How you insert strings into C++ mysql program"

Ok after a lot of trial and error I figured it out.

This is what it needs to be
"INSERT INTO list VALUES ('','" + input.c_str() + "','tespassword')"

But this throws some errors upon compiling so you have to compile the string before using it

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
        string sql;
        sql ="INSERT INTO md5 VALUES ('','";
        sql +=input;
        sql += "','tespassword')";

then call it with

if (mysql_query(&mysql, sql.c_str()) == 0) {
cout << "Successful Insert\n";
}
else {
cout << "Failed Write\n";
}


I hope this helps others out I’ve spent all day working on this.
Last edited on Sep 23, 2009 at 8:59pm
Topic archived. No new replies allowed.