query.next()返回false

时间:2011-08-17 21:20:29

标签: sql qt

我在代码中使用了query.next()函数,但返回false。 我甚至在数据库中检查过,目前有4条记录。但代码只显示了一个。 但是,如果我在query.next()的代码之前使用query.valid(),则它不会显示任何记录 请帮忙

  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;

2 个答案:

答案 0 :(得分:1)

要检查查询是否成功,您应该在尝试调用first / next / last之前测试QSqlQuery :: exec()或QSqlQuery :: isActive()的返回值(当您将查询字符串传递给构造函数时)对于QSqlQuery,查询已经执行,因此,您需要使用QSqlQuery :: isActive())。

first() next() last()如果他们将查询放在有效记录上,则返回true,你不要必须分别测试 isValid()。由于 first()也是一个定位函数,除非你想跳过第一条记录,否则你可以直接读取该值而不直接调用 next()

由于您可能希望将“invoice-info”表中的字段添加到查询中,因此我保留了子查询(使用IN而不是在评论中已经回答的=)。

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());
} 

答案 1 :(得分:0)

尝试

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