使用QT中的QSqlQuery建立資料庫及使用QSqlTabelModel刪除,增加,修改資料庫
阿新 • • 發佈:2021-01-06
技術標籤:qt5
使用QT中的QSqlQuery建立資料庫及使用QSqlTabelModel刪除,增加,修改資料庫
1.QSqlDatabase
QSqlDatabase類提供了一個介面,用於通過連線訪問資料。QSqlDatabase的一個例項表示連線。該連線通過受支援的資料庫驅動程式之一提供對資料庫的訪問,該驅動程式派生自QSqlDriver。
1.1 建立一個數據庫示例如下
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName(QApplication::applicationDirPath ()+"/Test.db"); //如果本目錄下沒有該檔案,則會在本目錄下生成,否則連線該檔案
if (!db.open()) {
QMessageBox::warning(0, QObject::tr("Database Error"),
db.lastError().text());
return false;
}
編譯執行後,可以看到已經建立了該檔案:
建立成功後,該檔案預設為空的,然後就可以使用QSqlQuery類來操作該資料庫, QSqlQuery類使用的是SQL語句,如果只需要使用高層次的資料
2.QSqlQuery類介紹
通過exec()成員函式來執行DML(資料操作語言)語句,如SELECT、INSERT、UPDATE和DELETE,以及DDL(資料定義語言)語句等.
比如:
QSqlQuery query;
query.exec("DROP TABLE students"); //刪除名為students的表
建立表:
query.exec("CREATE TABLE students ("
"id INTEGER PRIMARY KEY AUTOINCREMENT, "
"name VARCHAR(40) NOT NULL, "
" score INTEGER NOT NULL, "
"class VARCHAR(40) NOT NULL)");
//建立一個students表,標題分別為id、name、score、class
3、使用QSqlTableModel對資料庫進行操作。
.h檔案如下:
#pragma once
#include <QtWidgets/QMainWindow>
#include "ui_database.h"
#include "QWFComboBoxDelegate.h"
#include "QWFloatSpinDelegate.h"
#include "QWIntSpinDelegate.h"
#include <QSql>
#include <QDataWidgetMapper>
#include <QStandardItemModel>
#include <QItemSelectionModel>
#include <QSqlTableModel>
#include <QSqlDatabase>
#include <QFileDialog>
#include <QMessageBox>
#include <QSqlError>
#include <QAction>
#include <QStyledItemDelegate>
class database : public QMainWindow
{
Q_OBJECT
public:
database(QWidget *parent = Q_NULLPTR);
public:
void openTable(); //開啟資料表
void getFilelNames(); //獲取欄位名稱,填充排序欄位的comBoBox
private:
void initconnect();
private slots:
void on_currentChanged(const QModelIndex ¤t, const QModelIndex &previous);
void on_currentRowChanged(const QModelIndex ¤t, const QModelIndex &previous);
void openDatabase(); //開啟資料庫
void on_addData(); //新增資料
void on_insertData(); //插入資料
void on_deleteDate(); //刪除資料
void on_saveDate(); //儲存資料
void on_cancelDate(); //取消shuj
private:
Ui::databaseClass ui;
QWIntSpinDelegate intSpinDelegate; //整性數
QWFloatSpinDelegate floatSpinDelegate; //浮點數
QWFComboBoxDelegate comboBoxDelegate; //列表選擇
QSqlDatabase DB; //資料庫連線
QSqlTableModel *thisTableModel; //資料模型
QItemSelectionModel *thisSelectionModel; //選擇模型
QDataWidgetMapper * dataMapper; //資料對映
};
.cpp實現檔案如下
#include "database.h"
//處理中文轉換
#if _MSC_VER >= 1600
#pragma execution_character_set("utf-8")
#endif
database::database(QWidget *parent)
: QMainWindow(parent)
{
ui.setupUi(this);
initconnect();
}
void database::openTable()
{//開啟資料表
thisTableModel = new QSqlTableModel(this, DB);//資料模型和資料庫關聯
thisTableModel->setTable("studInfo");//資料庫中的資料表和資料模型關聯
thisTableModel->setSort(thisTableModel->fieldIndex("studID"), Qt::AscendingOrder); //設定排序方式
thisTableModel->setEditStrategy(QSqlTableModel::OnManualSubmit); //設定編輯策略
if (!(thisTableModel->select())) //查詢資料
{
QMessageBox::warning(this, "錯誤", "開啟資料表錯誤,錯誤資訊\n" +
thisTableModel->lastError().text(), QMessageBox::Ok, QMessageBox::NoButton);
return;
}
//設定行標題
thisTableModel->setHeaderData(thisTableModel->fieldIndex("studID"), Qt::Horizontal, "工號");
thisTableModel->setHeaderData(thisTableModel->fieldIndex("name"), Qt::Horizontal, "姓名");
thisTableModel->setHeaderData(thisTableModel->fieldIndex("gender"), Qt::Horizontal, "性別");
thisTableModel->setHeaderData(thisTableModel->fieldIndex("departID"), Qt::Horizontal, "學院編號");
thisTableModel->setHeaderData(thisTableModel->fieldIndex("majorID"), Qt::Horizontal, "專業編號");
thisSelectionModel = new QItemSelectionModel(thisTableModel); //設定選擇模型
//選擇模型型號和模型關聯
connect(thisSelectionModel, SIGNAL(currentChanged(QModelIndex, QModelIndex)), SLOT(on_currentChanged(QModelIndex, QModelIndex)));
connect(thisSelectionModel, SIGNAL(currentRowChanged(QModelIndex, QModelIndex)), SLOT(on_currentRowChanged(QModelIndex, QModelIndex)));
ui.tableView->setModel(thisTableModel); //設定資料模型
ui.tableView->setSelectionModel(thisSelectionModel); //設定選擇模型
//設定自定義代理
ui.tableView->setItemDelegateForColumn(thisTableModel->fieldIndex("gender"), &comboBoxDelegate);
//建立介面元件與資料模型的欄位之間的資料對映
dataMapper = new QDataWidgetMapper;
dataMapper->setModel(thisTableModel);
dataMapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit); //設定資料模型和介面元件間更新的方式
//介面元件與資料模型的具體欄位之間的連線
dataMapper->addMapping(ui.uiStudID, thisTableModel->fieldIndex("studID"));
dataMapper->addMapping(ui.uiName, thisTableModel->fieldIndex("name"));
dataMapper->addMapping(ui.uiGenDer, thisTableModel->fieldIndex("gender"));
dataMapper->addMapping(ui.uiDepartID, thisTableModel->fieldIndex("departID"));
dataMapper->addMapping(ui.uiMajorID, thisTableModel->fieldIndex("majorID"));
dataMapper->toFirst(); //移動到首記錄
}
void database::getFilelNames()
{
}
void database::initconnect()
{
connect(ui.openDatabase, &QAction::triggered, this, &database::openDatabase); //開啟資料庫
connect(ui.uiAddDete, &QAction::triggered, this, &database::on_addData); //增加資料
connect(ui.uIinsertDate, &QAction::triggered, this, &database::on_insertData); //插入資料
connect(ui.uiDeleteDate, &QAction::triggered, this, &database::on_deleteDate); //刪除資料
connect(ui.uiCancelData, &QAction::triggered, this, &database::on_cancelDate); //取消更改資料
connect(ui.uiSaveData, &QAction::triggered, this, &database::on_saveDate); //儲存資料
}
void database::on_currentChanged(const QModelIndex & current, const QModelIndex & previous)
{
}
void database::on_currentRowChanged(const QModelIndex & current, const QModelIndex & previous)
{
dataMapper->setCurrentIndex(current.row()); //更新資料對映行號
}
void database::openDatabase()
{//開啟資料庫
QString aFile = QFileDialog::getOpenFileName(this, "選擇資料庫檔案"/*, "SQLite資料庫(*.db *.db3)",QString("*.db")*/);
if (aFile.isEmpty())
{
return;
}
DB = QSqlDatabase::addDatabase("QSQLITE"); //新增SQLITE驅動
DB.setDatabaseName(aFile);
if (!DB.open())
{
QMessageBox::warning(this, "錯誤", "開啟資料庫失敗", QMessageBox::Ok, QMessageBox::NoButton);
}
//開啟資料表
openTable();
}
void database::on_addData()
{//新增資料
thisTableModel->insertRow(thisTableModel->rowCount(), QModelIndex());
QModelIndex curIndex = thisTableModel->index(thisTableModel->rowCount() - 1, 1);
thisSelectionModel->clearSelection(); // 清空選擇
thisSelectionModel->setCurrentIndex(curIndex, QItemSelectionModel::Select);
int currow = curIndex.row(); //獲取當前行號
thisTableModel->setData(thisTableModel->index(currow, 0), 100000 + thisTableModel->rowCount());
thisTableModel->setData(thisTableModel->index(currow, 2), "男");
}
void database::on_insertData()
{//插入資料
QModelIndex curIndex = ui.tableView->currentIndex();
thisTableModel->insertRow(curIndex.row(), QModelIndex());
thisSelectionModel->clearSelection();//清除已有選擇
thisSelectionModel->setCurrentIndex(curIndex, QItemSelectionModel::Select);
}
void database::on_deleteDate()
{//刪除當前選項
QModelIndex curIndex = thisSelectionModel->currentIndex();
thisTableModel->removeRow(curIndex.row());
}
void database::on_saveDate()
{
bool res = thisTableModel->submitAll();
if (!res)
{
QMessageBox::warning(this, "錯誤", "儲存資料錯誤,錯誤資訊\n" +
thisTableModel->lastError().text(), QMessageBox::Ok, QMessageBox::NoButton);
}
}
void database::on_cancelDate()
{//取消修改
thisTableModel->revertAll();
}