Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Copies of QSqlQuery share the same bound values



  • When I try to copy prepared QSqlQuery with assign or copy constructor and bind to them different values with bindValue they both will have the same bound value, one which was bound last. Is it the case of implicit sharing? Though this class is not listed as implicitly shared. I wasn't able to find anything in docs. What should I do to make independent copies of a query? I'm using Qt 5.13.2. Here is the test code:

    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE", "test");
    db.setDatabaseName("text.sqlite3");
    db.open();
    QSqlQuery createQuery(db);
    createQuery.exec("CREATE TABLE if not exists test"
                                              "(test_id integer)");
    QSqlQuery query1(db);
    query1.prepare("INSERT INTO test (test_id) VALUES(:test_id)");
    query1.bindValue(":test_id", 1);
    qDebug() << query1.boundValue(":test_id"); //this returns 1
    QSqlQuery query2(query1); //the same with QSqlQuery query2 = query1;
    query2.bindValue(":test_id", 2);
    qDebug() << query1.boundValue(":test_id") << query2.boundValue(":test_id"); //both return 2
    

  • Lifetime Qt Champion

    Create a bug report, with a proper minimal compilable example (use SQLite in-memory db) and assign it to me. For now simply use two distinct queries and prepare both.


  • Moderators

    Call QSqlQuery::clear as appropriate.



  • @kshegunov Which query should I clear? As I understand, clear will remove prepared statement from query. But I need to get two prepared queries with different bound values.


  • Moderators

    @Skogach said in Copies of QSqlQuery share the same bound values:

    @kshegunov Which query should I clear? As I understand, clear will remove prepared statement from query. But I need to get two prepared queries with different bound values.

    Yes that's correct and I'm sorry I just looked more carefully at the code. You should file a bug report if one isn't already in the tracker, this is not how it's intended to work. The copy constructor should create a copy, not keep an internal reference to the other query. As a workaround I'd just prepare the second query separately.


  • Lifetime Qt Champion

    Create a bug report, with a proper minimal compilable example (use SQLite in-memory db) and assign it to me. For now simply use two distinct queries and prepare both.



  • @Christian-Ehrlicher I created bug report , but I couldn't find how to assign it, so I mentioned you in comments.


  • Lifetime Qt Champion

    Thx. Will take a look on it and hope it will go into 5.15 (even we as opensource user currently don't have an advantage currently but this hopefully changes somehow in the near future)


Log in to reply