测试QSQLITE:
![](https://i-blog.csdnimg.cn/blog_migrate/e961842a49669b3dbc7a9eb77f030132.png)
先要创建db文件:
![](https://i-blog.csdnimg.cn/blog_migrate/c271c7f4769dbc71a2a4c4d233b95ff1.png)
myWidget.cpp
#include "widget.h"
#include "ui_widget.h"
#include<QDebug>
#include<QSqlDatabase>//数据库
#include<QMessageBox>
#include<QSqlError>//sql错误信息
#include<QSqlQuery>//sql语句类
#include<QVariantList>//泛型
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
//先创建info.db文件,再操作
ui->setupUi(this);
//打印Qt支持的数据库驱动
qDebug()<<QSqlDatabase::drivers();
//添加QSQLITE数据库
QSqlDatabase db= QSqlDatabase::addDatabase("QSQLITE");
//设置数据库
db.setDatabaseName("../info.db");
//打开数据库
if(db.open()==false)
{
QMessageBox::information(this,"失败",db.lastError().text());
return;
}
//创建表
//id integer primary key autoincrement 累加
QSqlQuery query;
query.exec("create table student(id integer primary key autoincrement ,name varchar(255),age int,score int)");
//插入数据
query.prepare("insert into student(id,name,age,score)values(?,?,?,?)");
QVariantList idlist;
idlist<<8<<9<<10;
QVariantList namelist;
namelist<<"xiaoming"<<"xiaolong"<<"xiaojiang";
QVariantList agelist;
agelist<<11<<28<<33;
QVariantList scorelist;
scorelist<<59<<60<<65;
query.addBindValue(idlist);
query.addBindValue(namelist);
query.addBindValue(agelist);
query.addBindValue(scorelist);
query.execBatch();
}
Widget::~Widget()
{
delete ui;
}
//删除
void Widget::on_pushButton_clicked()
{
QString name= ui->lineEdit->text();
QString str=QString("delete from student where name='%1'").arg(name);
QSqlQuery query;
QSqlDatabase db=QSqlDatabase::database();
if(db.isOpen()==true)
{
qDebug()<<"数据库打开";
bool is= query.exec("BEGIN TRANSACTION");
if(is==true)
{
qDebug()<<"事务开启成功";
}
}
query.exec(str);
}
//确认
void Widget::on_pushButton_2_clicked()
{
QSqlQuery query;
bool is= query.exec("COMMIT");
if(is==true)
{
qDebug()<<"确认成功";
}
}
//取消
void Widget::on_pushButton_3_clicked()
{
QSqlQuery query;
bool is= query.exec("ROLLBACK");
if(is==true)
{
qDebug()<<"取消成功";
}
}
//遍历
void Widget::on_pushButton_4_clicked()
{
QSqlQuery query;
//遍历查找
query.exec("select * from student where id<1006");
//一行一行遍历
while(query.next())
{
//取出当前行内容
qDebug()<<query.value(0).toInt()
<<query.value(1).toString()
<<query.value("age").toInt()
<<query.value("score").toInt();
}
}