Dec 19, 2018 at 5:23pm UTC
Is this what you mean?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
// Example program
#include <iostream>
#include <string>
int main()
{
bool condition1 = false ;
bool condition2 = true ;
bool condition3 = true ;
std::string query = "select" ;
if (condition1)
query += " x " ;
else
query += " a " ;
query += "from" ;
if (condition2)
query += " y " ;
else
query += " b " ;
query += "where" ;
if (condition3)
query += " z" ;
else
query += " c" ;
std::cout << "Executing: " << query << std::endl;
}
Alternative:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// Example program
#include <iostream>
#include <string>
int main()
{
std::string columns = "*" ;
std::string tables = "tab" ;
std::string condition = "Country=\'Spain\'" ;
std::string query = "select " + columns + " from " + tables + " where " + condition;
std::cout << "Executing: " << query << std::endl;
}
Executing: select * from tab where Country='Spain'
Also, be careful about letting user input influence what goes into a SQL query -- don't want SQL injection attacks.
Last edited on Dec 19, 2018 at 5:31pm UTC
Dec 19, 2018 at 6:41pm UTC
I think the alternative is more what I'm trying to do. I'll do some playing with it and see. The sqlite tutorial at tutorialspoint uses C code so anything with a string yells at me. Also, I'm just trying to learn this stuff right now, I don't plan on leaving it so vulnerable once I can actualy understand it.
Thank you very much
Dec 19, 2018 at 6:58pm UTC
I've never used sqlite, but if it's written in C, that means it you probably have to do something like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// Example program
#include <iostream>
#include <string>
int main()
{
std::string columns = "*" ;
std::string tables = "tab" ;
std::string condition = "Country=\'Spain\'" ;
std::string query = "select " + columns + " from " + tables + " where " + condition;
some_sqlite_function(query.c_str());
}
.c_str() returns a const char*.
Last edited on Dec 19, 2018 at 6:58pm UTC
Dec 19, 2018 at 7:06pm UTC
Probably. I saw somebody on SO make a reference to c_str (). Sqlite is written in C so I guess you'll probably be right. I'll have to check in the morning. Thanks!