0

I have a test.db database on my project directory, which I'm trying to insert data into. The database is connected, but I can't seem to insert data in it. The query is not executed at all (it seems), since the qDebug shows "Bad".

QSqlDatabase connectDB(){
    QSqlDatabase db= QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName("test.db");
    return db;

}

void planner::on_dataSend_clicked()
{
    QSqlDatabase datba = connectDB();
    if (datba.open()){
        qDebug()<< "DB Suc";
    } else{
        qDebug() << "DB Fail";
    }
    QString what = ui->addPlan->text();
    QSqlQuery qry;
    qry.prepare("insert into plan values :what");
    qry.bindValue(":what",what);
    if (qry.exec()){
             qDebug()<< "Good";
             qry.clear();

          } else{
             qDebug()<<"Bad";
             qDebug()<<qry.lastError();
             qry.clear();

          }
    datba.close();
    ui->addPlan->clear();


}

I'm using DB Browser for SQLite, and this is the database

The error that QSqlError shows is parameter count mismatch here

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
  • Assuming that the table contains only 1 column, you are missing parentheses in the sql statement: `qry.prepare("insert into plan values (:what)");` – forpas Mar 21 '22 at 15:47
  • I added the paranthses too, but the problem still persists. Still the same error.. :( – burrito-san Mar 21 '22 at 16:52
  • How many columns does the table have? – forpas Mar 21 '22 at 16:53
  • only 1, the plan column. – burrito-san Mar 21 '22 at 17:12
  • @burrito-san Use the full path of the .db, in the case of sqlite open it will always return true since if the database does not exist then it will be created. That's probably the cause of the error: The test.db in your code points to another folder so the db is created but not the table causing your insert to fail. – eyllanesc Mar 21 '22 at 22:37

1 Answers1

0

On SQLITE table, there is a default column as a primary key called rowid, you need to spécify the column that you want to add like this:

qry.prepare("insert into plan (column_name) values (:what)");
Yanis600
  • 71
  • 9