Qt SQL :qt建立数据库 查询数据(调试有效)

要在QT中使用SQL,首先需要包含sql模块:

QT += sql

二:新建一个.h文件

#ifndef SQLCONNECTION_H
#define SQLCONNECTION_H

#include <QMessageBox>
#include <QSqlDatabase>
#include <QSqlQuery>

class sqlConnection
{
public:
    sqlConnection();
};

static bool createConnection()
{
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName("my.db");
    if (!db.open()) {
        QMessageBox::critical(0, "Cannot open database1",
                              "Unable to establish a database connection.", QMessageBox::Cancel);
        return false;
    }
    QSqlQuery query;

    // 创建public表
    query.exec("create table student (id int primary key, "
                       "name varchar, course int)");
    query.exec("insert into student values(1, '李强', 11)");
    query.exec("insert into student values(2, '马亮', 11)");
    query.exec("insert into student values(3, '孙红', 12)");
    return true;
}


#endif // SQLCONNECTION_H

3:在.main函数中调用(自己也可以在其他的地方调用 使用open函数)

#include "widget.h"
#include "solution.h"
#include "sqlconnection.h"
#include <QApplication>
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    if (!createConnection()) return 1;  // 数据库打开一定要在创建ui前面
    Widget w;
    solution sum;
     w.show();
    return a.exec();
}

4:在.cpp中调用(注意 自己在ui中添加 tableView 控件 和在.h文件中添加 QSqlTableModel *model;)

#include "widget.h"
#include "ui_widget.h"
#include "sqlconnection.h"

//SQL need
#include <QSqlQueryModel>
#include <QSqlTableModel>
#include <QSqlRelationalTableModel>
#include <QTableView>
#include <QDebug>
#include <QMessageBox>
#include <QSqlError>

//#include "threadfromqthread.h"
#include <threadfromqthread.h>

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

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

对于数据库的操作

// 提交修改按钮
void Widget::on_pushButton_clicked()
{
    // 开始事务操作

    model->database().transaction();
    if (model->submitAll()) {
        if(model->database().commit()) // 提交
            QMessageBox::information(this, tr("tableModel"),
                                     tr("数据修改成功!"));
    } else {
        model->database().rollback(); // 回滚
        QMessageBox::warning(this, tr("tableModel"),
                             tr("数据库错误: %1").arg(model->lastError().text()),
                             QMessageBox::Ok);
    }

}

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

// 查询按钮,进行筛选
void MainWindow::on_pushButton_5_clicked()
{
    QString name = ui->lineEdit->text();

    // 根据姓名进行筛选,一定要使用单引号
  //  model->setFilter(QString("name = '%1'").arg(name));
  //  model->select();
    QSqlQuery query;
    quint8 i;
    i=ui->lineEdit_2->text().toInt();
    query. exec( QObject :: tr( "select * from student where id = %1" ). arg( i ));
    if (! query. next())
            qDebug()<< "none" ;
    else
            qDebug()<< query. value( 0 ). toInt()<< query. value( 1 ). toString()<< query. value( 2 ). toString();
}

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

// 按id升序排列按钮
void Widget::on_pushButton_7_clicked()
{
    //id字段,即第0列,升序排列
    model->setSort(0, Qt::AscendingOrder);
    model->select();

}

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

}
// 删除选中行按钮
void Widget::on_pushButton_4_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 Widget::on_pushButton_3_clicked()
{
    // 获得表的行数
   int rowNum = model->rowCount();
   int id = 10;

    // 添加一行
    model->insertRow(rowNum);
    model->setData(model->index(rowNum, 0), id);
    // 可以直接提交
    model->submitAll();
}

调试有效 调试不同的 可以留下邮箱,可以给你们发过去代码。我开始调试的时候遇到的坑是 在mian函数中调用的时候 打开数据库的时间比创建UI的界面晚。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

七 六 伍

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

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

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

打赏作者

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

抵扣说明:

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

余额充值