本文主要是介绍QT:搭配tablewidget的数据库编程,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
pro:QT += core gui sql
widget.ui
main.cpp
#include "widget.h"
#include <QApplication>int main(int argc, char *argv[])
{QApplication a(argc, argv);Widget w("./student.db");w.show();return a.exec();
}
widget.h
#ifndef WIDGET_H
#define WIDGET_H#include <QWidget>
#include <QSqlDatabase> //数据库连接
#include <QSqlQuery> //执行SQL语句
#include <QSqlError> //具体错误
#include <QDebug>namespace Ui {
class Widget;
}class Widget : public QWidget
{Q_OBJECTpublic:explicit Widget(QString filename,QWidget *parent = 0);~Widget();void showInfo();private slots:void on_pb_add_clicked();void on_pb_update_clicked();void on_pb_delete_clicked();private:Ui::Widget *ui;QString db_file_name; //数据库文件名QSqlDatabase db_student; //数据库名
};#endif // WIDGET_H
widget.cpp
#include "widget.h"
#include "ui_widget.h"
#include <QFile>
#include <QMessageBox>Widget::Widget(QString filename,QWidget *parent) :QWidget(parent),ui(new Ui::Widget),db_file_name(filename)
{ui->setupUi(this);setWindowTitle("学生信息系统");setFixedSize(800,600);QFile file(db_file_name);if(!file.exists()){db_student = QSqlDatabase::addDatabase("QSQLITE"); //建立到SQLITE数据库的连接db_student.setDatabaseName(db_file_name); //设置数据库文件名//打开数据库if (!db_student.open()){qDebug() << "打开数据库失败1";}else{qDebug() << "打开数据库成功1";}//QSqlQuery用于SQL语句的执行,对返回结果的使用//要指定使用的数据库的连接 db_studentQSqlQuery sql_query(db_student);//创建数据库的表QString str_query = "create table Student (id varchar(64) PRIMARY KEY, name varchar(64), gender varchar(64), age int)";//执行SQL语句if (!sql_query.exec(str_query)){qDebug() << str_query << " failed";qDebug() << sql_query.lastError().text();}//向数据库的student表插入数据 方式1str_query = "insert into Student values('2309260001', '张三', '男', 15)";if (!sql_query.exec(str_query)){qDebug() << str_query << " failed";qDebug() << sql_query.lastError().text();}//向数据库的student表插入数据 方式2str_query = "insert into Student values(?,?,?,?)";//准备SQL的语句sql_query.prepare(str_query);//绑定待定的数据,取代SQL语句里的 "?"sql_query.addBindValue("2309260002");sql_query.addBindValue("李四");sql_query.addBindValue("男");sql_query.addBindValue(16);if (!sql_query.exec()){qDebug() << str_query << " failed";qDebug() << sql_query.lastError().text();}//向数据库的student表插入数据 方式3str_query = "insert into Student values(:id, :name, :gender, :age)";sql_query.prepare(str_query);//绑定待定的数据sql_query.bindValue(":id", "2309260003");sql_query.bindValue(":name", "王五");sql_query.bindValue(":gender", "女");sql_query.bindValue(":age", 17);if (!sql_query.exec()){qDebug() << str_query << " failed";qDebug() << sql_query.lastError().text();}}else{db_student = QSqlDatabase::addDatabase("QSQLITE");//设置数据库文件的名字db_student.setDatabaseName(db_file_name);//打开数据库if (!db_student.open()){qDebug() << "打开数据库失败2";}else{qDebug() << "打开数据库成功2";}}ui->tableWidget->setColumnCount(4); //设置列数为4QStringList list;list << "学号" << "姓名" << "性别" << "年龄";ui->tableWidget->setHorizontalHeaderLabels(list);//显示数据库的内容showInfo();}Widget::~Widget()
{delete ui;
}void Widget::showInfo()
{QSqlQuery sql_query(db_student); //连接数据库,执行SQL操作QString str_query = "select * from Student";if(!sql_query.exec(str_query)){QMessageBox::information(this,"数据库操作错误",sql_query.lastError().text());return;}QList<QStringList> lists; //链表while(sql_query.next()){QStringList tmp;for(int i = 0;i < 4;i++){tmp << sql_query.value(i).toString(); //value为一条数据中的一个,tmp存放一整条数据:学号 、姓名 、性别 、年龄}lists.append(tmp); //存放所有数据(全部条),lists存放的条数为数据库的行数(一条为一行)}ui->tableWidget->setRowCount(lists.size()); //根据数据库里的记录的条数来设置行数//设置显示的数据库记录的内容for(int i = 0;i < lists.size();i++) //行{for(int j = 0;j < 4;j++) //列{ui->tableWidget->setItem(i,j,(new QTableWidgetItem(lists.at(i).at(j)))); //第i条第j个数据的内容}QTableWidgetItem *item = ui->tableWidget->item(i,0); //设置id不能被用户编辑item->setFlags(item->flags() & (~Qt::ItemIsEditable));}
}//新增
void Widget::on_pb_add_clicked()
{if(ui->pb_add->text() == "新增"){int row = ui->tableWidget->rowCount(); //获取实际行数,三条数据为3行ui->tableWidget->insertRow(row); //增加行数,索引从0开始为第一行,索引为3实际为第4行ui->pb_add->setText("提交");ui->pb_delete->setEnabled(false);ui->pb_update->setEnabled(false);}else{int row = ui->tableWidget->rowCount(); //新增一行后获取行数row--; //索引要减一才为所在新增行QSqlQuery sql_query(db_student);QString str_query = "insert into Student values(?,?,?,?)";sql_query.prepare(str_query);int count = 0;sql_query.addBindValue(ui->tableWidget->item(row,count++)->data(0).toString()); //idsql_query.addBindValue(ui->tableWidget->item(row,count++)->data(0).toString()); //namesql_query.addBindValue(ui->tableWidget->item(row,count++)->data(0).toString()); //gendersql_query.addBindValue(ui->tableWidget->item(row,count++)->data(0).toInt()); //ageif(!sql_query.exec()){qDebug() << str_query << " failed";qDebug() << sql_query.lastError().text();}ui->pb_add->setText("新增");ui->pb_delete->setEnabled(true);ui->pb_update->setEnabled(true);showInfo(); //刷新主界面的显示}
}//修改
void Widget::on_pb_update_clicked()
{int row = ui->tableWidget->currentRow(); //用户点击的所在行qDebug() << "row = " << row;if(row < 0){qDebug() << "wrong row number = " << row;return;}QSqlQuery sql_query(db_student);QString str_query = "update Student set name = ?,gender = ?,age = ? where id = ?";sql_query.prepare(str_query);sql_query.addBindValue(ui->tableWidget->item(row,1)->data(0).toString()); //name,所在行的索引为1的数据sql_query.addBindValue(ui->tableWidget->item(row,2)->data(0).toString()); //gendersql_query.addBindValue(ui->tableWidget->item(row,3)->data(0).toInt()); //agesql_query.addBindValue(ui->tableWidget->item(row,0)->data(0).toString()); //idif(!sql_query.exec()){qDebug() << str_query << " failed";qDebug() << sql_query.lastError().text();}showInfo();
}//删除
void Widget::on_pb_delete_clicked()
{int row = ui->tableWidget->currentRow(); //用户点击的所在行qDebug() << "row = " << row;if(row < 0){qDebug() << "wrong row number = " << row;return;}QSqlQuery sql_query(db_student);QString str_query = "delete from Student where id = ?";sql_query.prepare(str_query);sql_query.addBindValue(ui->tableWidget->item(row,0)->data(0).toString()); //idif(!sql_query.exec()){qDebug() << str_query << " failed";qDebug() << sql_query.lastError().text();}showInfo();}
结果
新增
修改
删除
这篇关于QT:搭配tablewidget的数据库编程的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!