QSqlquery結果集使用記錄
知識點:
query = new QSqlquery(db); 或者 query = QSqlquery::QSqlquery(db); 執行query.exec(str);成功后,query就包含了結果集,可以直接操作query指針,來讀取QSqlResult結果集中的內容
Query常用函數:
seek(int n) :query指向結果集的第n條記錄; first() :query指向結果集的第一條記錄; last() :query指向結果集的最后一條記錄; next() :query指向下一條記錄,每執行一次該函數,便指向相鄰的下一條記錄; previous() :query指向上一條記錄,每執行一次該函數,便指向相鄰的上一條記錄; record() :獲得現在指向的記錄; value(int n) :獲得屬性的值。其中n表示你查詢的第n個屬性,比方上面我們使用“select * from student”就相當於“select id, name from student”,那么value(0)返回id屬性的值,value(1)返回name屬性的值。該函數返回QVariant類型的數據,關於該類型與其他類型的對應關系,可以在幫助中查看QVariant。 at() :獲得現在query指向的記錄在結果集中的編號。
Size()函數無法返回結果集個數,返回-1
原因是函數本身問題,Qt幫助索引中描述如下:
int QSqlQuery::size () const Returns the size of the result (number of rows returned), or -1 if the size cannot be determined or if the database does not support reporting information about query sizes. Note that for non-SELECT statements (isSelect() returns false), size() will return -1. If the query is not active (isActive() returns false), -1 is returned. To determine the number of rows affected by a non-SELECT statement, use numRowsAffected(). See also isActive(), numRowsAffected(), and QSqlDriver::hasFeature().
翻譯:
返回結果的大小(返回的行數),如果無法確定大小或數據庫不支持有關查詢大小的報告信息,則返回-1。注意,對於非select語句(isselect()返回false),size()將返回-1。如果查詢未處於活動狀態(is active()返回false),則返回-1。
要確定受非select語句影響的行數,請使用numrowsAffected()。
解決方法:
//----------獲取結果集大小----------// if (query.last()) { qDebug()<<"結果集大小="<<query.at() + 1; } query.first();//重新定位指針到結果集首位 query.previous();//如果執行query.next來獲取結果集中數據,要將指針移動到首位的上一位。