无法从Qt Mac os中的SQLite数据库获取数据

时间:2015-07-16 12:51:36

标签: macos qt sqlite

我遇到了问题:

连接到SQLite数据库,写了一个请求

#include "schedule_edit.h"
#include "ui_schedule_edit.h"
#include <QComboBox>
#include <QtSql>
#include <QMessageBox>
#include <QSqlError>
#include <functions.h>
#include <QStringListModel>

Schedule_edit::Schedule_edit(QWidget *parent)
    : QWidget(parent), ui(new Ui::Schedule_edit)
{
  ui->setupUi(this);

  ui->tableWidget->setColumnWidth(1, 150);

  QStringList list;
  model = new QStringListModel();

  QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
  db.setDatabaseName("/Users/andreymityulin/Desktop/S2.sqlite");

  QSqlQuery query;

  if (db.isOpen())
  {

    query.exec("SELECT OVERALL FROM LESSONS_NAMES_5_9");

    QSqlRecord rec = query.record();

    while (query.next())
    {
        list << query.value(rec.indexOf("OVERALL")).toString();
    }

    model->setStringList(list);

    ui->listView->setModel(model);

    db.close();
  }

}

但我不知道为什么没有收到数据。 我确保正确输入DB的路径。 请帮我纠正代码!

1 个答案:

答案 0 :(得分:0)

调试正在发生的事情。检查查询是否正确执行,或者打印错误。此外,您只需value(0)即可访问第一个值。

if(!query.exec("SELECT OVERALL FROM LESSONS_NAMES_5_9"))
{
    qDebug() << query.lastError().text(); 
}

while (query.next())
{
    list << query.value(0).toString();
}

更新

由于错误是“内存不足而无法执行语句”,请尝试准备查询。

...
QSqlQuery query;
query.prepare("SELECT OVERALL FROM LESSONS_NAMES_5_9");

if(!query.exec())
{
    qDebug() << query.lastError().text(); 
}

while (query.next())
{
    list << query.value(0).toString();
}

更新2

您最好在需要之前创建QSqlQuery,而不是清除查询。当它超出范围时,它将自动清除。

来自QtDocs:

  

void QSqlQuery :: clear()

     

清除结果集并释放查询持有的所有资源。将查询状态设置为非活动状态。你应该很少需要调用这个函数。

相关问题