#include "ui_widget.h"Widget::Widget(QWidget *parent) :QWidget(parent),ui(new Ui::Widget)
{ui->setupUi(this);//判断是否有该数据库if(!db.contains("stuInfo.db")){//说明数据库不存在 则创建db=QSqlDatabase::addDatabase("QSQLITE");//增加一个数据库,驱动为sqlite3//给创建的数据库设置数据库名db.setDatabaseName("stuInfo");}//打开数据库if(!db.open()){QMessageBox::information(this,"","打开数据库失败");return;}//创建数据库表//实例化一个执行sql语句的对象QSqlQuery query;//准备sql语句QString sql="create table if not exists stu_info_table(""id integer primary key autoincrement,""numb integer,""name varchar(20),""sex varchar(4),""score integer)";//执行sql语句if(query.exec(sql)){QMessageBox::information(this,"","创建数据库表成功");}else{QMessageBox::information(this,"","创建数据库表失败");return;}on_showBtn_clicked();
}Widget::~Widget()
{delete ui;
}//添加按钮对应的槽函数处理
void Widget::on_addBtn_clicked()
{//获取ui界面上学生信息int numb=ui->numEdit->text().toUInt();QString name=ui->nameEdit->text();QString sex=ui->sexEdit->text();int score=ui->scoreEdit->text().toUInt();//判断用户是否填写完整信息if(numb==0||name.isEmpty()||sex.isEmpty()||score==0){QMessageBox::information(this,"","请将信息填写完整");return;}//实例化一个执行sql语句的对象QSqlQuery query;//准备sql语句QString sql=QString("insert into stu_info_table (numb,name,sex,score)""values(%1,'%2','%3',%4)").arg(numb).arg(name).arg(sex).arg(score);//执行sql语句if(query.exec(sql)){QMessageBox::information(this,"","添加成功");}else{QMessageBox::information(this,"","添加失败");}ui->numEdit->clear();ui->nameEdit->clear();ui->sexEdit->clear();ui->scoreEdit->clear();ui->tableWidget->clearContents();on_showBtn_clicked();
}//显示按钮对应槽函数处理
void Widget::on_showBtn_clicked()
{//准备sql语句QSqlQuery query;QString sql="select * from stu_info_table";if(!query.exec(sql)){QMessageBox::information(this,"","查询失败");return;}//所查询的信息就已经存放到query对象中int i=0;//记录行号while(query.next()){for(int j=0;j<query.record().count();j++){ui->tableWidget->setItem(i,j,new QTableWidgetItem(query.value(j+1).toString()));}i++;//行数递增}
}void Widget::on_deleteBtn_clicked()
{int numb=ui->numEdit->text().toUInt();QSqlQuery query;QString sql=QString("delete from stu_info_table where numb=%1").arg(numb);if(query.exec(sql)){QMessageBox::information(this,"","执行成功");}else{QMessageBox::information(this,"","执行失败");}ui->tableWidget->clearContents();on_showBtn_clicked();
}void Widget::on_revbtn_clicked()
{QSqlQuery query;int numb=ui->numEdit->text().toUInt();QString name=ui->nameEdit->text();QString sex=ui->sexEdit->text();int score=ui->scoreEdit->text().toUInt();if(!name.isEmpty()){QString sql=QString("update stu_info_table set name='%1' where numb=%2").arg(name).arg(numb);query.exec(sql);}if(!sex.isEmpty()){QString sql=QString("update stu_info_table set sex='%1' where numb=%2").arg(sex).arg(numb);query.exec(sql);}if(!score){QString sql=QString("update stu_info_table set score=%1 where numb=%2").arg(score).arg(numb);query.exec(sql);}ui->tableWidget->clearContents();on_showBtn_clicked();
}