【问题标题】:QT SQLite select returns no dataQT SQLite 选择不返回数据
【发布时间】:2015-11-02 13:53:05
【问题描述】:

我的 QT SQL 选择不返回任何数据:

 //connect DB
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName("C:/temp/atsakymai_1.db");
if (!db.open())
{
    qDebug() << "Connection error!!!";
}
QSqlQuery query;
query.prepare("SELECT * FROM transportas");
if (!query.exec())
{
     qDebug() << "SQL error: "<< query.lastError().text() << endl;
}

qDebug() << query.executedQuery();
qDebug() << query.result();
qDebug() << query.size();

query.first();
while (query.next())
{
    qDebug() << "found " << endl;
}

试图写这样的路径 - C:\temp\atsakymai_1.db,但结果相同:

query.result - 0x3c6ed8
query.size - -1

我整天都在谷歌上寻找任何解决方案,但它没有帮助,仍然不知道我的代码有什么问题。

在 SELECT 之前尝试了 INSERT,INSERT 没有错误,但 SELECT 仍然没有返回任何内容:

 QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName("C:/temp/atsakymai_1.db");

if (!db.open())
{
    qDebug() << "error!!!";
}

QSqlQuery query(db);

query.exec("insert into t_transportas (transportas) values ('asdasd22')");
query.exec("SELECT id, transportas FROM 't_transportas'");

qDebug() << query.executedQuery();
qDebug() << query.result();
qDebug() << query.size();
if (query.size()> 0)
{
    qDebug() << "found " << 
}

【问题讨论】:

  • QT 是 QuickTime,Qt 是框架......你需要准备查询吗,如果你只是尝试会发生什么:QSqlQuery query("SELECT * FROM transportas;"); bool success = query.exec(); while(query.next() == true) { qDebug() &lt;&lt; query.value(0).toString(); }
  • @Alchazar 你能确认 db.open() 工作正常吗? query.exec() 是否返回 true?您是否有一个可以连接到该文件以检查其中是否有数据的 SQLite 资源管理器类型的应用程序?我喜欢使用“从 mytable 中选择计数 (*)”,因为它总是返回一行,前提是该表存在于数据库中。
  • @TheBadger 尝试了您的代码,结果相同 - 一无所获。
  • @MichaelVincent select count 返回 0。我使用 SQLite 数据库浏览器来探索数据库。数据正确,代码中使用的相同查询在资源管理器中正常工作。
  • @Alchazar 使用 count(*) 返回的 0 表明该表存在,但为空。假设没有报告其他错误。

标签: c++ qt sqlite


【解决方案1】:

发现问题出在哪里,QSqlQuery::size() 函数不起作用,它总是返回-1。所以不要使用这个函数来查找行数。代替这个使用 .first() .next() 函数。此代码正常工作:

 QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName("C:/temp/atsakymai_1.db");
if (!db.open())
{
    qDebug() << "error!!!";
}

QSqlQuery query(db);
query.prepare("SELECT id, transportas FROM 't_transportas'");
if (!query.exec())
{
     qDebug() << "SQL error: "<< query.lastError().text() << endl;
}
    query.first();
    qDebug() << "found: " << endl;
    while (query.next())
    {

        qDebug() << query.value("id").toString() << ". " << query.value("transportas").toString();

    }

在这里找到答案: QtSQL + Sqlite and support for .size() function?

【讨论】:

    猜你喜欢
    • 2014-01-21
    • 1970-01-01
    • 1970-01-01
    • 2011-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-17
    相关资源
    最近更新 更多