![見出し画像](https://assets.st-note.com/production/uploads/images/140200264/rectangle_large_type_2_44d2205be9e406dedae495e2b5088fa0.png?width=1200)
QSqlQueryでSelect文を指定したらQSqlQuery::value: not positioned on a valid recordと言うエラーが返ってきた話
突拍子もないですが、メモッとこうかなと、突拍子もなく思ったので書いておきます。
QSqlQuery query(QString("SELECT Count(*) FROM %1").arg(DB_mapTableName)); if (query.value(0) == 0) { query.prepare(QString("INSERT OR IGNORE INTO %1 (%2, %3, %4, %5, %6, %7 VALUES(:%2, :%3, :%4, :%5, :%6, :%7").arg( DB_mapTableName, DB_mapId, DB_mapName, DB_mapRow, DB_mapCol, DB_mapPixmap, DB_mapLoad)); query.bindValue(QString(":%1").arg(DB_mapName), QString("worldmap")); query.bindValue(QString(":%1").arg(DB_mapRow), QVariant(32)); query.bindValue(QString(":%1").arg(DB_mapCol), QVariant(32)); query.bindValue(QString(":%1").arg(DB_mapPixmap), QByteArray()); query.bindValue(QString(":%1").arg(DB_mapLoad), QByteArray()); if (query.exec()) { if (model->select()) { qDebug() << "insert is success"; } else { qDebug() << model->lastError().text(); } } else { qDebug() << query.lastError().text(); } }
で、QSqlQuery::value: not positioned on a valid recordと言われました。
これは、queryを利用した後に、next()を呼んでいないことによって発生するエラーなのです。QSqlQueryオブジェクトでSELECTクエリを実行した後、結果セット内の最初のレコードに移動するためにnext()メソッドを呼び出す必要があります。
QSqlを利用すると、こういう不思議ちゃんな仕様によく出会う。