前面兩節主要介紹SQL接口層,這節我們來初窺用戶接口層。
在之前已經說了用戶接口層提供從數據庫數據到用戶數據表示的窗體的映射。
除了QSqlQuery類外,Qt還提供了三種用於訪問數據庫的高層類。
類名 | 用途 |
QSqlQueryMdoel | 基於任意SQL語句的只讀模型 |
QSqlTableModel | 基於單個表的讀寫模型 |
QSqlReltionalTableModel | QSqlTableModel的子類,增加了外鍵支持 |
下面的代碼是在上一節的基礎上添加的。
1、QSqlQueryMdoel
QSqlQueryModel *model = new QSqlQueryModel();
model->setQuery("SELECT table_user.user_id, table_group.group_name FROM table_group,"
"table_user WHERE table_group.group_id=table_user.group_id");
for(int i = 0; i < model->rowCount(); i++)
{
qDebug() << model->record(i).value("user_id").toString();
qDebug() << model->record(i).value("group_name").toString();
}
這段代碼使用了多表查詢,目的是得到工號和對應組別的數據。
這裏順帶提一提SQLite 多表查詢的方法。
多表查詢方法:
sqlite3可以有多種多表查詢方法,比如 select (select * from table2) from table1 where xxx=xxx;
select table1.abc from table1,table2 where table1.xxx=table2.xxx;
或這種
select table1.abc from table1 inner join table2 on table1.xxx=table2.xxx;
在使用QSqlQueryModel::setQuery()進行查詢語句的設置後(執行後得到查詢結果集),我們就可以使用record(i)訪問每一條單獨的記錄了。
2、QSqlTableModel
QSqlTableModel tablemodel; //單表查詢
tablemodel.setTable("table_user"); //綁定表
tablemodel.setFilter("group_id=1"); //設置查詢條件
tablemodel.select(); //查詢
for(int i = 0; i < tablemodel.rowCount(); i++)
{
qDebug() << tablemodel.record(i).value(1).toString();
}
QSqlTableModel的使用也比較簡單。注意的一點是,他只能操作單個表。
因爲table_user表只有2個字段。所以通過value()指定字段索引的時候,直接寫了索引值。在操作大量數據的時候,最好通過索引指定字段。如:
int UserID_Index = tablemodel.record().indexOf("user_id");
qDebug() << tablemodel.record(i).value(UserID_Index).toString();
或者
tablemodel.record(i).value("user_id").toString();
注意,一定要調用select()。否則不能得到查詢結果集
3、QSqlReltionalTableModel
QSqlRelationalTableModel *model = new QSqlRelationalTableModel();
model->setTable("table_user");
model->setRelation(1, QSqlRelation("table_group", "group_id", "group_id")); //表明table_group.group_id是table_group的主鍵
model->setHeaderData(0, Qt::Horizontal, tr("工號"));
model->setHeaderData(1, Qt::Horizontal, tr("組別"));
if(!model->select())
{
QMessageBox::critical(this, tr("錯誤提示"), model->lastError().text(), QMessageBox::Cancel);
}
QSqlReltionalTableModel的用法和QSqlTableModel大同小異。第四行和第五行的作用相當爲model的表頭指定列設定名稱(相當於數據庫字段的別名)
在這裏附上程序源代碼下載鏈接:qt_數據庫_初窺用戶接口層
以上純屬個人學習筆記,如果哪裏錯了,希望提出。願和大家一起共同學習,一起進步。我的郵箱地址是:[email protected]