QT:实现连接数据库,并进行简单的增删改查等功能

实现结果:

这个小的程序实现主要分为两个三个部分:

  1. 添加一个connection.h文件,实现数据库的连接
  2. 在ui界面拖入相应的控件,构件图形化界面
  3. 在mainwindow.cpp中现实相应的代码操作(需要注意函数都是按键的槽的clicked()函数)

在实现项目前,首先需要在.pro中添加:

QT       += sql

一,connection.h代码实现

#ifndef CONNECTION_H
#define CONNECTION_H
#include <QMessageBox>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QDebug>

static bool createConnection()
{
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    db.setHostName("127.0.0.1");
    db.setPort(3333);
    db.setDatabaseName("mydata");
    db.setUserName("root");
    db.setPassword("root");
    if (!db.open())
    {
        QMessageBox::critical(0, QObject::tr("无法打开数据库"),
                     "无法创建数据库连接!", QMessageBox::Cancel);
            return false;
    }
    // 下面来创建表
    // 如果 MySQL 数据库中已经存在同名的表,那么下面的代码不会执行
    QSqlQuery query(db);

    // 使数据库支持中文
    query.exec("SET NAMES 'Latin1'");
    // 创建 course 表
    query.exec("create table course (id int primary key, "
               "name varchar(20), teacher varchar(20))");
    query.exec("insert into course values(0, '数学', '张老师')");
    query.exec("insert into course values(1, '语文', '李老师')");
    query.exec("insert into course values(2, '英语', '王老师')");
    return true;
}
#endif
// CONNECTION_H

二,mainwindow.h代码实现

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

namespace Ui {
class MainWindow;
}

class QSqlTableModel;

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = nullptr);
    ~MainWindow();

private slots:
    void on_on_pushButton_clicked_clicked();

    void on_on_pushButton_2_clicked_clicked();

    void on_on_pushButton_7_clicked_clicked();

    void on_on_pushButton_8_clicked_clicked();

    void on_on_pushButton_5_clicked_clicked();

    void on_on_pushButton_4_clicked_clicked();

    void on_on_pushButton_3_clicked_clicked();

    void on_on_pushButton_6_clicked_clicked();

private:
    Ui::MainWindow *ui;
    QSqlTableModel *model;
};
#endif // MAINWINDOW_H

三,main.cpp代码实现

#include "mainwindow.h"
#include <QApplication>
#include "connection.h"
#include <QProcess>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QProcess process;
    process.start("D:/mysql/mydwl/bin/mysqld.exe");
    if (!createConnection())
        return 1;
    MainWindow w;
    w.show();

    return a.exec();
}

四,mainwindow.cpp代码实现

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QSqlQuery>
#include <QSqlTableModel>
#include <QSqlError>
#include <QMessageBox>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    model = new QSqlTableModel(this);
    model->setTable("course");
    model->select(); // 设置编辑策略
    model->setEditStrategy(QSqlTableModel::OnManualSubmit);
    ui->tableView->setModel(model);
}

MainWindow::~MainWindow()
{
    delete ui;
}

// 提交修改按钮
void MainWindow::on_on_pushButton_clicked_clicked()
{
        // 开始事务操作
        model->database().transaction();
        if (model->submitAll())
        {
            model->database().commit(); //提交
        }
        else
        {
            model->database().rollback(); //回滚
            QMessageBox::warning(this, tr("tableModel"), tr("数据库错误: %1").arg(model->lastError().text()));
        }
}


// 撤销修改按钮
void MainWindow::on_on_pushButton_2_clicked_clicked()
{
    model->revertAll();
}

// 查询按钮,进行筛选
void MainWindow::on_on_pushButton_7_clicked_clicked()
{
        QString name = ui->lineEdit->text(); //根据姓名进行筛选,一定要使用单引号
        model->setFilter(QString("teacher = '%1'").arg(name));
        model->select();
}

// 显示全表按钮
void MainWindow::on_on_pushButton_8_clicked_clicked()
{
   model->setTable("course");
   model->select();
}

// 按 id 降序排列按钮
void MainWindow::on_on_pushButton_6_clicked_clicked()
{
    model->setSort(0, Qt::DescendingOrder);
    model->select();
}

// 按 id 升序排列按钮
void MainWindow::on_on_pushButton_5_clicked_clicked()
{
    //id 属性,即第 0 列,升序排列
    model->setSort(0, Qt::AscendingOrder); model->select();
}

// 删除选中行按钮
void MainWindow::on_on_pushButton_4_clicked_clicked()
{
    // 获取选中的行
    int curRow = ui->tableView->currentIndex().row();
    // 删除该行
    model->removeRow(curRow);
    int ok = QMessageBox::warning(this,tr("删除当前行!"), tr("你确定删除当前行吗?"),QMessageBox::Yes, QMessageBox::No);
    if(ok == QMessageBox::No)
    {
        // 如果不删除,则撤销
        model->revertAll();
    }
    else
    {
        // 否则提交,在数据库中删除该行
        model->submitAll();
    }
}

// 添加记录按钮
void MainWindow::on_on_pushButton_3_clicked_clicked()
{
    // 获得表的行数
    int rowNum = model->rowCount();
    // 添加一行
    model->insertRow(rowNum);
    model->setData(model->index(rowNum,0),rowNum);
}

  • 10
    点赞
  • 117
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 7
    评论
### 回答1: 你好,关于qttableview数据库添加数据的问题,可以采用以下步骤: 1. 连接数据库:在代码中使用QSqlDatabase类连接你的数据库。 2. 准备SQL语句:使用QSqlQuery类准备一个SQL语句,用于向表中添加数据。 3. 绑定参数:如果SQL语句中有参数,可以使用QSqlQuery类的bindValue()方法绑定参数。 4. 执行SQL语句:使用QSqlQuery类的exec()方法执行SQL语句,即可将数据插入到数据库表中。 以下是一个简单的示例代码,可以用于向表中添加数据: ```python import sys from PyQt5.QtWidgets import QApplication, QMainWindow, QTableView from PyQt5.QtSql import QSqlDatabase, QSqlQuery, QSqlTableModel class MyMainWindow(QMainWindow): def __init__(self): super().__init__() # 连接数据库 db = QSqlDatabase.addDatabase('QMYSQL') db.setHostName('localhost') db.setUserName('root') db.setPassword('password') db.setDatabaseName('mydatabase') if not db.open(): print("无法连接数据库") sys.exit(-1) # 准备SQL语句 query = QSqlQuery() query.prepare("INSERT INTO mytable (name, age) VALUES (:name, :age)") query.bindValue(":name", "张三") query.bindValue(":age", 25) # 执行SQL语句 if not query.exec(): print("无法插入数据") sys.exit(-1) # 创建表格视图 table_view = QTableView() model = QSqlTableModel() model.setTable("mytable") model.select() table_view.setModel(model) # 将表格视图添加到主窗口 self.setCentralWidget(table_view) if __name__ == '__main__': app = QApplication(sys.argv) window = MyMainWindow() window.show() sys.exit(app.exec_()) ``` 注意,这只是一个简单的示例代码,实际情况可能会更加复杂,需要根据具体的情况进行调整。 ### 回答2: 在Qt中,要向TableView中添加数据库数据,首先需要建立一个数据库连接。可以使用QSqlDatabase类来实现,需要指定数据库的类型、主机名、端口号、用户名和密码等信息。 ```cpp #include <QtSql> #include <QTableView> QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE"); // 指定数据库类型为SQLite db.setDatabaseName("my_database.db"); // 数据库文件名 if (!db.open()) { qDebug() << "无法建立数据库连接!"; return; } QTableView *tableView = new QTableView; QSqlTableModel *model = new QSqlTableModel; model->setTable("my_table"); // 表名 model->select(); // 从数据库中选取数据 tableView->setModel(model); // 将数据模型设置为TableView的模型 model->insertRow(model->rowCount()); // 插入一行数据 model->setData(model->index(0, 0), "John"); // 设置第一列数据为"John" model->setData(model->index(0, 1), 25); // 设置第二列数据为25 model->submitAll(); // 提交数据数据库 tableView->show(); ``` 以上代码的作用是在TableView中显示数据库中的数据,并向数据库中的表中添加一行数据,然后将更改提交到数据库。用户可以根据需要修改相应的数据库信息、表名和插入的数据内容。 ### 回答3: 在Qt中,要将数据添加到TableView中,需要先连接到数据库并打开相应的表。首先,需要使用QSqlDatabase类连接到数据库,具体步骤如下: 1. 首先,需要包含必要的头文件: #include <QtSql/QSqlDatabase> #include <QtSql/QSqlQuery> #include <QtSql/QSqlError> #include <QtSql/QSqlTableModel> 2. 然后,需要创建一个QSqlDatabase对象,并设置相应的数据库驱动和连接参数: QSqlDatabase db = QSqlDatabase::addDatabase("驱动类型"); db.setHostName("主机名"); db.setDatabaseName("数据库名"); db.setUserName("用户名"); db.setPassword("密码"); 3. 接下来,需要使用open()函数打开数据库连接: if(db.open()) { // 连接成功 } else { // 连接失败 QString error = db.lastError().text(); } 4. 连接成功后,我们可以使用QSqlTableModel类作为TableView的模型,并将其设置为tableView的模型: QSqlTableModel *model = new QSqlTableModel(this, db); model->setTable("表名"); model->select(); tableView->setModel(model); 5. 现在,我们可以使用QSqlQuery类来执行SQL语句,将数据添加数据库中: QSqlQuery query(db); query.prepare("INSERT INTO 表名 (字段1, 字段2, ...) VALUES (:值1, :值2, ...)"); query.bindValue(":值1", 值1); query.bindValue(":值2", 值2); // 绑定更多的值... if(query.exec()) { // 添加成功 } else { // 添加失败 QString error = query.lastError().text(); } 6. 最后,我们可以更新tableView显示的数据: model->select(); 以上就是在Qt中向TableView添加数据的基本步骤。需要注意的是,要根据具体的数据库设置合适的驱动类型,并确保正确设置连接参数、表名和字段名,以及正确的SQL语句和绑定值。
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大学生毕设

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值