2

I have the following code in my C++ program:

query_state = mysql_query(connection, "select * from cplpl");

if I want to replace the table name,cplpl, by a variable in my C++ program, how do I do it?

basically, I've created

string tblnm="cplpl";

but then if I run

query_state = mysql_query(connection, "select * from tblnm");

it looks for the table tblnm. I tried $tblnm also like you can do in Perl, but that doesn't work either

Is there a way I can fix this? thx!

EDIT: If I rewrite this as follows:

string tblnm="test";
string qrycd="select * from " +tblnm;
 query_state = mysql_query(connection, qrycd.c_str());

it works, however, if I want to add a where clause

string qrycd1="where fname like '%Bob%';";

and rewrite the code as

string qrycd="select * from " +tblnm +qrycd1;
 query_state = mysql_query(connection, qrycd.c_str());

I get an error..

itcplpl
  • 780
  • 4
  • 18
  • 29
  • of course you want to be careful if tblnm is user input and not just insert it into the query. See this question on parametirizing db names and table names in mysql: http://stackoverflow.com/questions/6656636/is-there-any-safe-way-to-parameterize-database-names-in-mysql-queries – Doug T. Aug 23 '11 at 17:35
  • 3
    You need to look into what C++ is and how it works. Its that simple. I recommend reading an introduction book – Martin Kristiansen Aug 23 '11 at 17:36

5 Answers5

8

This should work:

query_state = mysql_query(connection, ("select * from " + tblnm).c_str());
Eelke
  • 20,897
  • 4
  • 50
  • 76
  • +1 for being the only one to remember `c_str()` including myself. – Seth Carnegie Aug 23 '11 at 17:34
  • 1
    @itcplpl: when you do tblnm +qrycd1 you are missing whitespace between the tablename and the where keyword. When building queries dynamically allways take care to add spaces. Changing the code to tblnm + " " + qrycd1 should solve the issue. It will be a good debugging aid for yourself to output the query you create to standard out or a log so you can see what the actual query looks like. Then you would easily spot such problems yourself. – Eelke Aug 23 '11 at 19:26
  • @Eelke, thanks very much for the constructive suggestion- I will do so. and yes, it worked :-) – itcplpl Aug 23 '11 at 19:32
2

You can simply use operator+ of string:

query_state = mysql_query(connection, ("select * from " + tblnm).c_str());

You probably should read a good beginner's C++ book.

Community
  • 1
  • 1
Seth Carnegie
  • 73,875
  • 22
  • 181
  • 249
2

In C++ + is used for string concatenation.

string tblnm="cplpl";
query_state = mysql_query(connection, "select * from " + tblnm);

Don't try random things from other languages, read some C++ documentation.

john
  • 85,011
  • 4
  • 57
  • 81
2

you need to construct the string.. look into this

http://www.cplusplus.com/reference/string/string/operator+=/

Martin Kristiansen
  • 9,875
  • 10
  • 51
  • 83
0

Looks like you lost space after table name

string tblnm="cplpl ";
vromanov
  • 881
  • 6
  • 11