Important: Please read the Qt Code of Conduct -

QSqlQuery error

  • Hi,
    I've spent quite some time trying to figure out what's wrong with this code. Whenever I run it I get the following messages:
    The database is open!
    QSqlQuery::value: not positioned on a valid record

    The code:

        QSqlDatabase db;
        db = QSqlDatabase::addDatabase ("QSQLITE");
        db.setDatabaseName ("C:/Programming/Qtsamples/Image_from_DB/db.db"); ();
        QSqlQuery query;
        if(! ())
            qDebug() << "The database is NOT open!";
            qDebug() << "The database is open!";
        query.prepare ("SELECT Pic FROM Items");
        query.exec ();
        query.first ();
    	QByteArray ByteArray;
    	ByteArray = query.value (1).toByteArray ();
        QPixmap Pixmap = QPixmap();
        Pixmap.loadFromData (ByteArray);
        db.close ();
    	ui->label->setPixmap (Pixmap);
        ui->label->show ();

    Please help me to make it positioned on a valid record!
    Thank you.

  • Moderators

    You select one column from the table, but try to retrieve the second column from the resultset, try:


    Additional (potential) problems exist in your code:

    • In example, you don't handle the return value of your QSqlDatabase::first call, it's supposed to tell you whether you're properly positioned at the first record or not.
    • You call QSqlDatabase::open twice, you can use QSqlDatabase::isOpen to check if your database was properly opened instead of trying to open it again.
    • You don't handle the return value of QSqlQuery::exec as well.
    • There is no need to really prepare the query before execution, you don't intend to use it multiple times with different bindings.
    • You close your database after executing the query. Usually the idea is to open/close the database once and have multiple queries executed on the same database instance.

    Kind regards.

  • Thank you. it worked.

Log in to reply