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

QSqlQuery weird error



  • In the following code, q.prepare() and q.exec() both return false and qDebug outputs - " Parameter count mismatch"

    void Database::deleteAllRecords(const QString& db_name, const QString& table)
    {
    	auto err = initDb("deleteData", db_name);
    	Q_ASSERT(err.type() == QSqlError::NoError);
    
    	auto db = QSqlDatabase::database("deleteData");
    
    	auto q = QSqlQuery{ db };
    	Q_ASSERT(q.driver()->hasFeature(QSqlDriver::NamedPlaceholders));
    
    	auto zxda = q.prepare(QLatin1String{ R"(
    		DELETE FROM :table
    	)" });
    
    	//the same with addBindValue
    	q.bindValue(":table", table);
    
    	auto ok = q.exec();
    
    	qDebug() << q.lastError().text();
    }
    

    but when I supply hardcoded table name then it all works just fine:

    void Database::deleteAllRecords(const QString& db_name)
    {
    	auto err = initDb("deleteData", db_name);
    	Q_ASSERT(err.type() == QSqlError::NoError);
    
    	auto db = QSqlDatabase::database("deleteData");
    
    	auto q = QSqlQuery{ db };
    	Q_ASSERT(q.driver()->hasFeature(QSqlDriver::NamedPlaceholders));
    
    	auto zxda = q.prepare(QLatin1String{ R"(
    		DELETE FROM cache
    	)" });
    
    	auto ok = q.exec();
    
    	qDebug() << q.lastError().text();
    }
    
    

    Db driver is QSQLITE. Does anyone have an idea what's going on there?



  • @krzysieklfc
    I could be off, because I've never used SQLite, but you can only put placeholder-bind-variables where the SQL actually allows it, it's not just "text-like-macro-substitution". I think you will find DELETE FROM <table-name> does not allow a "bound variable" there, it has to be literal, hence the behaviour you see. Essentially I think you can use the bound-variables for column values & literals, but not e.g. for a table or database name etc.



  • Thanks for reply.

    I managed to solve this problem with the following:

    	auto prepare_string = QString{ "DELETE FROM %1" }.arg(table);
    	auto ok = q.prepare(prepare_string);
    
    	auto ok = q.exec();
    
    

Log in to reply