PDA

View Full Version : creating query string from variables



locus
9th April 2007, 11:47
I am trying to create a string with the values of some variables as follows

const char *quer = "insert into comm_records (caller_id,userID,c_area,c_duration,c_date) values ('"+number+"','"+userID+"','"+area+"','"+duration+"','"+date+"')";

all the identifiers between the + signs are variables, and i am trying to form a string with the valuse of those variables. i keep getting the following error


: error C2110: '+' : cannot add two pointers

non of the variables are pointers, some are integers and some are strings, could someone give me some pointers on how to achieve what i want to do.

Thanks.

jacek
9th April 2007, 13:21
I am trying to create a string with the values of some variables as follows
Make sure you validate all of those variables or your application might be vulnerable to the SQL injection attack. If you use Qt, consider using QSqlQuery::bindValue().


non of the variables are pointers, some are integers and some are strings, could someone give me some pointers on how to achieve what i want to do.
In C++ string literals are treated as pointers, so you can't concatenate them using + operator. Instead you have to use strcat() function, std::string class or QString (if you are using Qt).

The second problem is that you can't concatenate a string and integer (or any other type). First you have to convert the latter to a string, for example using boost::lexical_cast or std::stringstream. In Qt you can use QString::arg() and QString::number().

Kumosan
16th April 2007, 08:50
First of all, jacek is right when he points to the risk of injection attacks.
So building an sql query directly with input from user data is potentially dangerous.
However, if you don't care or if it does not apply to you, I like the following way to build complicated strings:



QString queryString;
QTextStream queryStream(&queryString);

queryStream
<< "INSERT INTO comm_records (caller_id, userID) VALUES ('"
<< number << "','"
<< userID << "');";


Afterwards you find your desired statement in queryString.