QT5 and SQLite3 “No query Unable to fetch row”

2019-07-09 05:52发布

问题:

i have a problem with my SQLite Database in QT5. I have table called "mytable" and im trying to save, change or load data there. The table looks like this (CODE):

"mytable" ("id" INTEGER PRIMARY KEY  NOT NULL , "name" VARCHAR NOT NULL , "akcie" INTEGER NOT NULL )

Then im trying to work with this database like this (CODE):

void MainWindow::on_pushButton_save_clicked()
{
    QString jmeno, IDcko, ak;

    IDcko = ui->lineEdit_ID->text();
    jmeno = ui->lineEdit_Name->text();
    ak = ui->lineEdit_Akcie->text();

    open_connection();

    QSqlQuery query;
    query.prepare("INSERT INTO mytable(id, name, akcie) VALUES(id= \'"+ IDcko +"\', name= \'"+ jmeno +"\', akcie= \'"+ ak +"\')");

    if(query.exec())
    {
        QMessageBox::information(this, tr("SAVED"), tr("Some text."));
        close_connection();
    }
    else
    {
        QMessageBox::critical(this, tr("NOT SAVED"), query.lastError().text());
        qDebug() << query.lastError().text();
    }
}

In the same file im opening connection like this (CODE):

bool MainWindow::open_connection()
{
    QSqlDatabase database;
    database = QSqlDatabase::addDatabase("QSQLITE");
    database.setDatabaseName("‪..\\added\\test_table.sqlite");
    if(!database.open())
    {
        qDebug() << "not opened connection";
        return false;
    }
    else
    {
        qDebug() << "opened connection";
        return true;
    }
}

And im still getting error: "No query Unable to fetch row", i have been looking for the answer really hard but nothing worked. Could it be because of some includes or am I doing something wrong?

Thank you in advance for your help!

回答1:

You are not preparing the query right. Use bindings like:

query.prepare("INSERT INTO mytable(id, name, akcie) VALUES(:id, :name, :akcie)");
query.bindValue(":id", IDcko);
query.bindValue(":name", jmeno);
query.bindValue(":akcie", ak);    


标签: qt sqlite qt5