下面是一个简单的 Qt 数据库操作示例,展示了如何使用 Qt 的 QtSql
模块进行基本的数据库操作。该示例将使用 SQLite 数据库来存储联系人信息。
1. 项目结构
假设项目名为 DatabaseExample
,其结构如下:
DatabaseExample/
├── main.cpp
├── mainwindow.cpp
├── mainwindow.h
├── mainwindow.ui
└── databaseexample.pro
2. databaseexample.pro
文件
这是项目的 Qt 项目文件,内容如下:
QT += core gui sql
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
TARGET = DatabaseExample
TEMPLATE = app
SOURCES += main.cpp\
mainwindow.cpp
HEADERS += mainwindow.h
FORMS += mainwindow.ui
3. main.cpp
文件
这是应用程序的入口点,内容如下:
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
4. mainwindow.h
文件
这是主窗口的头文件,定义了用户界面和功能:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlError>
#include <QSqlTableModel>
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
private slots:
void on_addButton_clicked();
void on_deleteButton_clicked();
void on_updateButton_clicked();
private:
void setupDatabase();
void refreshTable();
Ui::MainWindow *ui;
QSqlDatabase db;
QSqlTableModel *model;
};
#endif // MAINWINDOW_H
5. mainwindow.cpp
文件
这是主窗口的实现文件,包含了功能的实现代码:
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QInputDialog>
#include <QMessageBox>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent), ui(new Ui::MainWindow)
{
ui->setupUi(this);
setupDatabase();
refreshTable();
}
MainWindow::~MainWindow()
{
db.close();
delete ui;
}
void MainWindow::setupDatabase()
{
db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName("contacts.db");
if (!db.open()) {
QMessageBox::critical(this, "Database Error", db.lastError().text());
}
QSqlQuery query;
query.exec("CREATE TABLE IF NOT EXISTS Contacts (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)");
}
void MainWindow::refreshTable()
{
model = new QSqlTableModel(this, db);
model->setTable("Contacts");
model->select();
ui->tableView->setModel(model);
}
void MainWindow::on_addButton_clicked()
{
bool ok;
QString name = QInputDialog::getText(this, tr("Add Contact"),
tr("Name:"), QLineEdit::Normal,
"", &ok);
if (ok && !name.isEmpty()) {
QSqlQuery query;
query.prepare("INSERT INTO Contacts (name) VALUES (:name)");
query.bindValue(":name", name);
if (!query.exec()) {
QMessageBox::warning(this, tr("Error"), query.lastError().text());
}
refreshTable();
}
}
void MainWindow::on_deleteButton_clicked()
{
QModelIndex index = ui->tableView->currentIndex();
if (index.isValid()) {
int id = model->data(model->index(index.row(), 0)).toInt();
QSqlQuery query;
query.prepare("DELETE FROM Contacts WHERE id = :id");
query.bindValue(":id", id);
if (!query.exec()) {
QMessageBox::warning(this, tr("Error"), query.lastError().text());
}
refreshTable();
} else {
QMessageBox::warning(this, tr("Delete Contact"), tr("Please select a contact to delete."));
}
}
void MainWindow::on_updateButton_clicked()
{
QModelIndex index = ui->tableView->currentIndex();
if (index.isValid()) {
int id = model->data(model->index(index.row(), 0)).toInt();
bool ok;
QString name = QInputDialog::getText(this, tr("Update Contact"),
tr("Name:"), QLineEdit::Normal,
model->data(index.sibling(index.row(), 1)).toString(), &ok);
if (ok && !name.isEmpty()) {
QSqlQuery query;
query.prepare("UPDATE Contacts SET name = :name WHERE id = :id");
query.bindValue(":name", name);
query.bindValue(":id", id);
if (!query.exec()) {
QMessageBox::warning(this, tr("Error"), query.lastError().text());
}
refreshTable();
}
} else {
QMessageBox::warning(this, tr("Update Contact"), tr("Please select a contact to update."));
}
}
6. mainwindow.ui
文件
使用 Qt Designer 创建用户界面,包含以下组件:
- 一个
QTableView
用于显示联系人列表。 - 三个
QPushButton
,分别为“添加”、“删除”和“更新”。
7. 编译和运行
- 使用 Qt Creator 打开项目。
- 编译并运行程序。
功能说明
- 添加联系人:点击“添加”按钮,输入联系人的名字,点击确认后将其添加到数据库中。
- 删除联系人:选择一个联系人,点击“删除”按钮,将其从数据库中移除。
- 更新联系人:选择一个联系人,点击“更新”按钮,可以修改其名字。
这个示例提供了一个基本的数据库操作功能,可以根据需要进一步扩展,例如添加更多字段或实现搜索功能。