2011-08-17 185 views
1

我在代碼中使用了query.next()函數,但它返回false。 我甚至在數據庫中檢查過,現在有4條記錄。但代碼只顯示一個。 但是如果我使用query.next()query.valid()代碼之前,那麼它不顯示任何記錄 請幫query.next()返回false

qDebug() << "entering payment: get all the unchecked invoices for user: " + user; 
    QStringList tmp; 
    QSqlQuery query(m_storageUserManager->database()); 
    m_storageUserManager->dumpTable(m_invoiceInfoTable); 
    m_storageUserManager->dumpTable(m_invoiceUserTable); 
    qDebug()<<"THE NAME OF THE INVOICE USER TABLE_----=-----------------"<<m_invoiceInfoTable; 
    qDebug()<<"THE NAME OF THE INVOICE USER TABLE_----=-----------------"<<m_invoiceUserTable; 
    query.prepare("SELECT invoice FROM "+ m_invoiceInfoTable +" WHERE invoice = (SELECT 
       invoice FROM "+ m_invoiceUserTable +" WHERE user=:user)"); 
// query.prepare("SELECT invoice FROM " + m_invoiceInfoTable + ","+ m_invoiceUserTable +" WHERE " + m_invoiceInfoTable + ".user = " + m_invoiceUserTable + ".:user"); 
    query.bindValue(":user", user); 
    query.exec(); 
    query.first(); 
    qDebug()<<"Unchecked invoices done!!! " ; 
    if(query.isValid()) { 
    do { 
     tmp.append(query.value(0).toString()); //as the value returned by value() is a QVariant so we need to change it to String. 
    } while(query.next()); 
    } else 
    tmp.append("No Unchecked invoice in the database"); 
    return tmp; 
+0

同一用戶的所有四條記錄? 'query.first()'返回'true'嗎? 'query.size()'返回什麼? –

+0

如果子查詢返回多於一行,則外部'where'應該有'in'而不是'='。 – Mat

回答

1

要檢查如果查詢成功,你應該測試返回值在嘗試調用first/next/last(當您將查詢字符串傳遞給QSqlQuery的構造函數時,該查詢已經執行,因此,您需要使用QSqlQuery :: exec()或QSqlQuery :: isActive ::活躍())。

第()下一個()最後()返回true,如果他們定位在有效記錄查詢,你不必測試isValid()的分開。由於第一個()也是一個定位函數,所以您可以在不調用next()之後直接讀取該值,除非您想跳過第一條記錄。

由於您可能希望將「invoice-info」表中的字段添加到您的查詢中,因此我保留子查詢(使用IN而不是=,因爲Mat已在註釋中回答)。

query.prepare(QString("SELECT invoice FROM %1 WHERE invoice " 
         "IN (SELECT invoice FROM %2 WHERE user=:user)") 
       .arg(m_invoiceInfoTable, m_invoiceUserTable));  
/* 
// Or with an inner join 
query.prepare(QString("SELECT %1.invoice FROM %1 " 
       "INNER JOIN %2 ON %1.invoice = %2.invoice " 
       "WHERE user=:user").arg(m_invoiceInfoTable, m_invoiceUserTable));*/  
query.bindValue(":user", user); 

if (!query.exec()) { 
    tmp.append("Query error: %1" + query.lastError().text()); 
} else if (!query.first()) { 
    tmp.append("No Unchecked invoice in the database"); 
} else { 
    do { 
     tmp.append(query.value(0).toString()); 
    } while(query.next()); 
} 
+0

非常感謝,它使用IN in place = – Puneet

0

嘗試

query.prepare("SELECT invoice FROM " + m_invoiceInfoTable + " WHERE user=:user"); 
+0

我很抱歉沒有發佈數據庫結構, 但實際上在發票信息表中沒有用戶字段使用invoiceUser連接到用戶字段表 – Puneet