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..

2
  • 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: stackoverflow.com/questions/6656636/… Commented Aug 23, 2011 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 Commented Aug 23, 2011 at 17:36

5 Answers 5

8

This should work:

query_state = mysql_query(connection, ("select * from " + tblnm).c_str());
Sign up to request clarification or add additional context in comments.

3 Comments

+1 for being the only one to remember c_str() including myself.
@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, thanks very much for the constructive suggestion- I will do so. and yes, it worked :-)
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.

Comments

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.

Comments

2

you need to construct the string.. look into this

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

1 Comment

look at @Seth_Carnegie's post
0

Looks like you lost space after table name

string tblnm="cplpl ";

Comments

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.