Unsolved Reusing QSqlQuery by using QSqlQuery::prepare()
-
Hello,
is possible to reuse an instance of QSqlQuery by redefinition of query by calling QSqlQuery::prepare(newSQL_string) after query.exec()?If yes, is it neccessary to clear previous data by calling some function like QSqlQuery::clear() or QSqlQuery::finish() or ... before I will call prepare() function?
Or is neccessary to use for each SQL query the new instance of QSqlQuery?
Assume the code like this:
query.prepare("INSERT INTO PERSONS (Name, City) VALUES ('John', 'Boston')");
if (query.exec()) {
query.prepare("SELECT * FROM CARS WHERE CAR_ID = 10");
query.exec();
} -
@PetrS82 Yes, no problem:
QSqlQuery query(dbConnection); if(query.exec("INSERT INTO PERSONS (Name, City) VALUES ('John', 'Boston')) { if(query.exec("SELECT * FROM CARS WHERE CAR_ID = 10")) { while(query.next()) { // do stuff... } } }
-
It's a good idea to call
QSqlQuery::finish
before you run your next prepare statement to tell the DB that it can release any locks or snapshots you may've acquired. -
@PetrS82 said in Reusing QSqlQuery by using QSqlQuery::prepare():
query.prepare("INSERT INTO PERSONS (Name, City) VALUES ('John', 'Boston')");
if (query.exec()) {
query.prepare("SELECT * FROM CARS WHERE CAR_ID = 10");
query.exec();
}Redefining the prepared statement query is a bad practice because it negates the objective of a prepared statement. Simply create another query object and keep your prepares linked to distinct query objects. If you are intent upon using a single query object then you might as well simply do immediate mode SQL in the exec("sql") fashion.
-
Unless you bind arguments, which arguably is much better than allowing for injection of invalid query data.