inside a for loop I need to perform "n" sprintf commands to compose a sql statement. For this, I´ve been using a vector<char *> with the values I need to replace inside (let´s call it) the base select string. This base select looks like...
"select col1, col2, col3 from tab1 where colA='%s' and colB='%s'"
My hope is/was that I would be able to replace one of the '%s' at a time. The program would find the first '%s' in the first step and replace it by vector[0], then, the second '%s' by vector[1] in the second step and so on. But the real effect I am facing is that sprintf is replacing the whole base select, so, at the end of the loop, my base select is just the value of the last item of the vector.
I would like to keep an implementation like this to make it generic since more classes will be using it and the base select of each differs in the select itself and in the number of parameters that need to be replaced. Yet could not find what I am missing. Can you help? Thanks.
You need to build up the query. I wouldn't bother with snprint (you shouldn't be using sprintf), use C++ in-memory streams.
For example:
1 2 3 4 5 6 7 8 9 10
std::ostringstream os;
os << "SELECT col1, col2, col3 FROM tab1 WHERE ";
for (size_t i = 0; i != columns.size(); ++i)
{
if (i != 0)
os << " AND "
os << "col" << char('A' + i) << "=\'" << column[i] << "\'";
}
std::string sql = os.str();
checking some older source code, we found a solution that was easier for us (since building the query would force us to change the database model to store the specific columns for the where clause for each different select. The columns at the where clause also varies and all these sql statements are stored in database instead of being hard coded).
Now we are formatting our base select with specific jokers like $0, $1, $2 instead of C++ '%s'. Then, we did the for loop as before, using sprintf to format just the vector index and call an extra function (replaceString) we have in our libraries: