如何同时访问同一个数据库中的不同表

how to access different tables from the same database simultaneously

我正在使用 Qt5 和 Sqlite3。我正在做一个日志功能。我有两个表,allBooks 定义如下:

CREATE TABLE IF NOT EXISTS allBooks (NAME VARCHAR(100) UNIQUE, AUTHOR VARCHAR(100) NOT NULL, UID VARCHAR(100) UNIQUE, QUANTITY INT NOT NULL);

和定义为的日志:
CREATE TABLE IF NOT EXISTS log (STUDENT VARCHAR(100) NOT NULL, UID VARCHAR(100) NOT NULL, ISSUED CHAR(11) NOT NULL, RETURNED CHAR(11) NOT NULL);

在列表视图中显示日志的日志对话框的构造函数如下所示:

model = new QStringListModel(this);

QStringList list;

QSqlQuery query1, query2;

query1.exec("SELECT * FROM log");

while(query1.next())
{
    QSqlRecord rec = query1.record();

    QString student = rec.value(0).toString(),
            uid = rec.value(1).toString(),
            issued = rec.value(2).toString(),
            returned = rec.value(3).toString();

    if(query2.exec("SELECT NAME FROM allBooks WHERE UID = " + uid))
        uid = query2.record().value(0).toString();
    else
        QMessageBox::critical(this, "Oops:", query2.lastError().text());

    if(returned == "Not yet returned")
        list << student + " issued " + uid + " on " + issued + " which is not returned yet";
    else
        list << student + " issued " + uid + " on " + issued + " and returned it on " + returned;
}

if(list.size() == 0)
{
    QMessageBox::critical(this, "Well...", "It seems that no book is issued");
    valid = false;
}
else
{
    model->setStringList(list);

    ui->listView->setModel(model);
}

循环的本质是我有本书的uid。我想知道我拥有其 uid 的书的名称。但我不知道该怎么做。 问题是,在输出中没有显示书名,也没有任何错误。两个表都在同一个数据库中。如何在不影响 query1 的情况下访问循环中的 allBooks 表?

您必须调用类似 query2.next() 的函数才能转到第一个返回的记录。

无论如何,让数据库将表连接在一起会更容易:

SELECT *
FROM log
JOIN allBooks USING (UID);