我使用以下代码使用 Qt 从 SQLite DB 获取数据:
QSqlQuery wordQuery( QString( "SELECT id, word FROM Words WHERE ref_id = :ref_id" ) );
wordQuery.bindValue( ":ref_id", refId );
wordQuery.setForwardOnly( true );
wordQuery.exec( );
while( wordQuery.next( ) ) {
// obtain data from `wordQuery` using QSqlQuery::value( )
}
该Words
表确实包含ref_id
字段等于所需值的行。我已经使用作为 Qt 演示应用程序提供的 sqlbrowser 进行了检查。但QSqlQuery::next( )
仅第一次返回 true,我无法获取其余行。
顺便说一句,在这里我发现了类似的问题,但对我来说向后迭代不起作用
下面我把整个功能代码:
QList<Word> LyricsMasterModel::fetchWords( const DbId &refId )
{
QList<Word> result;
if ( !db.isOpen( ) && !db.open( ) ) {
return result;
}
QSqlQuery wordQuery;
wordQuery.setForwardOnly( true );
wordQuery.prepare( QString( "SELECT id, word FROM %1 WHERE ref_id = :ref_id" )
.arg( WORDS_TABLE_NAME ) );
wordQuery.bindValue( ":ref_id", refId );
if ( !wordQuery.exec( ) ) {
qDebug( ) << "SQL QUERY ERROR:" << wordQuery.lastError( ).text( );
}
const QSqlRecord wordTuple = wordQuery.record( );
const int idIndex = wordTuple.indexOf( "id" );
Q_ASSERT( -1 != idIndex );
const int wordIndex = wordTuple.indexOf( "word" );
Q_ASSERT( -1 != wordIndex );
while (wordQuery.next()) {
Word word;
word.setId( wordQuery.value( idIndex ).toByteArray( ) );
word.setSongId( refId );
word.setWord( wordQuery.value( wordIndex ).toString( ) );
result << word;
}
db.close( );
return result;
}
解决方案:我没有找到问题的原因,但以下变体似乎是有效的变体:
QSqlQuery wordQuery;
wordQuery.prepare( QString( "SELECT id, word FROM %1 WHERE ref_id = :ref_id" )
.arg( WORDS_TABLE_NAME ) );
wordQuery.bindValue( ":ref_id", refId );
const bool res = wordQuery.exec( );
Q_ASSERT( res );
if ( wordQuery.last( ) ) {
do {
// do stuff
} while (wordQuery.previous());
}