qt链接sqlite轻型数据库
Posted 长安紫薯
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了qt链接sqlite轻型数据库相关的知识,希望对你有一定的参考价值。
#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轻型数据库的主要内容,如果未能解决你的问题,请参考以下文章