user2284538
user2284538

Reputation: 1

how put user input into a variable in an SQL statement using c/c++

I'm quite new in all this programming. But I wanted to know how to pass a variable value into an/a SQL/MYSQL statement in a C/C++ query code.

For example, I wanted to select from database: mysql_query(conn, "select * from ;"); Say that is a variable and receives user's input. How do I actually do that? Any idea will be greatly appreciated.

Upvotes: 0

Views: 3787

Answers (3)

zakinster
zakinster

Reputation: 10688

You could use std::string as other said, but you could also use sql::PreparedStatement which are a lot more safe :

sql::Connection *con;
sql::PreparedStatement *prep_stmt
const char* tableName = "foo";

prep_stmt = con->prepareStatement("SELECT * FROM ?");
prep_stmt->setString(1, tableName);
prep_stmt->execute();

When using prepared statement, the DBMS will parse and compile the statement as is and will bind the values of the parameters only at the execution of the statement. This allow you to reuse the same statement multiple times with different parameters but also offer you a strong protection against SQL injection since you let the DBMS take care of the parameters.

Upvotes: 3

MSalters
MSalters

Reputation: 179779

To make milleniumbug's warning more explicit: Google "SQL injection". The solution is prepared statements.

std::string sql = "select * from ?;". This is a statement which you can prepare and then execute. When preparing, MySQL finds the ?, and when executing you just need to provide a value for ?. MySQL will then insert the table name for you.

Upvotes: 2

Captain Obvlious
Captain Obvlious

Reputation: 20063

You can use std::string to easily build an SQL statement.

#include <string>

std::string CreateSelectStatement(const std::string& tableName)
{
    std::string  sql;

    sql = "select * from " + tableName + ";";

    return sql;
}

You can then use the string to query the database.

std::string sql(CreateSelectStatement("sometable"));

mysql_query(conn, sql.c_str()); 

Upvotes: 1

Related Questions