我正在使用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);
和log定义为:
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);
}
循环的本质是我拥有本书的内容。我想知道这本书的名字。但我不知道如何去做。 问题是,在输出中没有显示书名,也没有任何错误。两个表都在同一个数据库中。如何在不影响query1的情况下访问循环中的allBooks表?
答案 0 :(得分:0)
您必须调用类似query2.next()
的函数才能转到第一个返回的记录。
无论如何,让数据库一起加入表会更容易:
SELECT *
FROM log
JOIN allBooks USING (UID);