#include "studentdialog.h"
#include "ui_studentdialog.h"
StudentDialog::StudentDialog(QWidget *parent)
: QDialog(parent)
, ui(new Ui::StudentDialog)
{
ui->setupUi(this);
//程序启动时创建
createDB();
createTable();
queryTable();
}
StudentDialog::~StudentDialog()
{
delete ui;
}
void StudentDialog::createDB(){
//数据库驱动,默认在本机,链接地址用户名密码均可省略
db = QSqlDatabase::addDatabase("QSQLITE");
//没有会自动创建,已有会直接打开
db.setDatabaseName("stu.db");
if(db.open()){
qDebug() << "创建/打开数据库成功!";
}else{
qDebug() << "创建/打开数据库失败!";
}
}
void StudentDialog::createTable(){
QSqlQuery query;
QString str = QString("create table tb_student ("
"id int primary key not null,"
"name text not null,"
"score real not null)");
if(query.exec(str) == false){
qDebug() << str;
}else{
qDebug() << "创建表成功!"; //第一次创建,之后不会再创建
}
}
void StudentDialog::queryTable(){
QString str = QString("select * from tb_student");
model.setQuery(str);
ui->tableView->setModel(&model); //参数要地址
}
void StudentDialog::on_insertButton_clicked()
{
//从页面获取用户填写内容
QSqlQuery query;
int id = ui->idEdit->text().toInt();
QString name = ui->nameEdit->text();
double score = ui->scoreEdit->text().toDouble();
//占位符方式
QString str = QString("insert into tb_student values(%1,'%2',%3)")
.arg(id).arg(name).arg(score);
if(query.exec(str)==false){
qDebug() << str;
}else{
qDebug() << "插入记录成功!";
queryTable();
}
}
void StudentDialog::on_deleteButton_clicked()
{
QSqlQuery query;
int id = ui->idEdit->text().toInt();
QString str = QString("delete from tb_student where id = %1").arg(id);
if(query.exec(str)==false){
qDebug() << str;
}else{
qDebug() << "删除记录成功!";
queryTable();
}
}
void StudentDialog::on_updateButton_clicked()
{
QSqlQuery query;
int id = ui->idEdit->text().toInt();
QString name = ui->nameEdit->text();
double score = ui->scoreEdit->text().toDouble();
QString str = QString("update tb_student set name= '%1',score= %2 where id = %3")
.arg(name).arg(score).arg(id);
if(query.exec(str)==false){
qDebug() << str;
}else{
qDebug() << "修改记录成功!";
queryTable();
}
}
void StudentDialog::on_clearButton_clicked()
{
ui->idEdit->setText("");
ui->nameEdit->setText("");
ui->scoreEdit->setText("");
}
qt链接sqlite轻型数据库
最新推荐文章于 2023-06-10 20:03:46 发布