Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting a variable into a mysql table

I know how to insert non variable values into a MySql table (using C++):

Ex:

//Table person:
mysql_query(conn, "INSERT INTO MyTable VALUES (  '1', 'John', 'Kennedy')");
mysql_query(conn, "INSERT INTO MyTable VALUES (  '2', 'Dave', 'Chappelle')");
mysql_query(conn, "INSERT INTO MyTable VALUES (  '3', 'Arnold', 'Schwarzenegger')");
//Up to 100 rows of data...

What I would like to do is be able to insert a variable into a table with C++:

Ex:

i=0;
for(i=0; i < 100; i++)
{
mysql_query(conn, "INSERT INTO MyTable VALUES ( i, 'FirstName', 'LastName')"); 
}

Rather than having to manually type in 100 rows of data, I would like to be able to use a for loop, and increment a variable to create the rows for me.

Does anyone know how to insert a variable into a mysql database using C++?

like image 266
James Diaz Avatar asked Nov 26 '12 03:11

James Diaz


1 Answers

I am not too familiar with the syntax to get it to work, but the generic version of what you want is Prepared Statements. You make a statement which has variables as placeholders. These are later provided values and used.

Edit: You can find more information about prepared statement use in c++ at the MySQL website

// ...
sql::Connection *con;
sql::PreparedStatement  *prep_stmt
// ...

prep_stmt = con->prepareStatement("INSERT INTO test(id, label) VALUES (?, ?)");

prep_stmt->setInt(1, 1);
prep_stmt->setString(2, "a");
prep_stmt->execute();

prep_stmt->setInt(1, 2);
prep_stmt->setString(2, "b");
prep_stmt->execute();

delete prep_stmt;
delete con;
like image 96
Karthik T Avatar answered Sep 23 '22 20:09

Karthik T