Using string variables for sql query?

Is there a way to use string variables for my sql queries? Such as

1
2
  string a = "select x from y where z";
  string b = "select a from b where c";


Then use an if else based on user input to execute,one or the other. All the tutorials I have found use char* but I don't know anything about them.
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
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
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
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!
Topic archived. No new replies allowed.