I want to generate SQL queries from user input for inserting some data into a database.
The user may input anything. Is there a way in Qt to convert such user inputs in
"The user may input anything."
That doesn't give us much to go by, but I can give you an example of how I would set up a basic insert query.
// I assume you already have a QSqlDatabase object called 'db'
QSqlQuery query(db);
QString s = "INSERT INTO table (colA, colB) VALUES (:valA, :valB);"
query.prepare(s);
// You only need to prepare the query once
// To actually insert values into colA & colB, do this:
query.bindValue(":valA", QString("stuff to put in colA"));
query.bindValue(":valB", QString("other stuff for colB"));
query.exec();
query.finish(); // you probably don't even need this
The bindValue
method takes a QVariant
as its second argument (I used strings in my example, but you could use anything supported by the variant type). You just have to make sure the type of the values makes sense for the relevant columns in your database.
Also, I'm using the syntax from PostgreSQL for my example. I think it's standard, but you may need to change the parameter binding (the :valA
:valB
stuff) to match what your db engine expects.