2011-07-06 119 views
1

我决定为我的Qt应用程序测试sqlite数据库。qt sqlite选择语句

我已经创建了正确的语句(创建表等,并插入一些数据行)的SQLite数据库文件。 我的问题是,当我执行select语句时,我没有得到任何记录。

这是我使用的代码:

qq.sprintf("SELECT * from descriptors WHERE descriptors.id=%d ",idx); 
query.exec(qq); 
if(query.isSelect()){ 
    while (query.next()){ 

    int fff = query.value(0).toInt(); 

}}

的问题是,我从来没有while循环中获得。 query.next()似乎不起作用。

任何提示? 在此先感谢, Thodoris

p.s.我忘了写我的配置如此:Qt 4.7.3,Windows 7,Visual Studio 2008

+1

你不应该这样构造你的查询。 [改为使用绑定](http://www.sqlite.org/c3ref/bind_blob.html),否则[Little Bobby Tables](http://xkcd.com/327/)将再次出现。 – 2011-07-06 14:02:11

+0

感谢您的回答和漫画。我用mysql的这种查询构造并且工作正常。我会尝试使用绑定来看看会发生什么,我会更新 – theosem

+0

当然,它会正常工作。直到鲍比表出现。仅仅因为它工作正常并不意味着它没问题。这就像运行STOP标志。它有效直到有人死亡。 –

回答

2

除了发布错误hexa,query.isSelect()将始终返回true,即使查询失败。你需要检查exec()的结果:

QSqlQuery query; 
query.prepare("SELECT * FROM descriptors WHERE id = ?"); 
query.bindValue(0, idx); // assuming idx is an integer/long/QVariant value 

if(!query.exec()) 
{ 
    // Error Handling, check query.lastError(), probably return 
} 

// Note: if you don't return in case of an error, put this into the else{} part 
while(query.next()) 
{ 
    int fff = query.value(0).toInt(); 
} 
+0

感谢您的回答,但这也没有奏效。我想这不是语法的东西,但别的东西... 我会让你全部更新我的结果。 再次感谢 – theosem

+0

好的感谢解决了。有一些问题的组合。首先是绑定,然后是没有正确构造的数据库文件(保存为字符串的int)。再次感谢帮助解决这个问题 – theosem

0

在我的情况下,QSqlQueries的反向迭代工作。我认为这可能是QSQLite驱动程序实现中某处的错误。

QSqlQuery q = db.exec("SELECT * FROM Table"); 
if (q.last()) { 
    do { 
     // Do something with row... 
    } while (q.previous()); 
}