Qt World Summit: Submit your Presentation

[solved]Inserting values in QMysql

  • Hi. I've created a new Database called "people" and a new table in it called "table" with three columns (id, FirstName, LastName) but I have problem when i try to insert data in it.
    The table already has 3 records;

    Here is my programm :

    #include <QCoreApplication>
    #include <QDebug>
    #include <QtSql>
    int main(int argc, char *argv[])
        QCoreApplication a(argc, argv);
    QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
        qDebug() << "Opened";
        QString sQuery = "INSERT INTO table(id, FirstName, LastName) VALUES (:id, :FirstName, :LastName)";
        QSqlQuery qry;
        qry.bindValue(":id", 4);
        qry.bindValue(":FirstName", "Heather");
        qry.bindValue(":LastName", "Heather");
        qDebug() << "Closing";
        qDebug() << "Whoops! ERRROR";
        qDebug() << db.lastError();
    return a.exec(); 

    It runs with no errors but nothing is added to the table...

  • @killerman said:


    You should check the returned value of QSqlQuery::prepare() and QSqlQuery::exec()

  • i get false and false.

    The connection to database is good because i can read from it...

  • So it means you have error preparing the query.

    Do this

    bool result = qry.prepare(sQuery);
    if (!result) {
        qDebug() << qry.lastError();

  • QSqlError("1064", "QMYSQL3: Unable to prepare statement", "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'table(id, FirstName, LastName)VALUES (?, ?, ?)' at line 1")

  • @killerman said:


    I'm not 100% sure you can use table as table name.
    Anyway IIRC MySQL is case sensitive for table name if it runs on a case sensitive filesystem/OS (like Linux for example): check if the table name is correct

    Try to run the same query from a different MySQL client to verify the syntax

  • I've made another DB and it works fine.

    "table" was the problem. Thanks a lot :)

  • You're welcome.

    Remember to mark the thread as SOLVED

Log in to reply