QSqlDatabase-QSQLITE

该代码示例展示了在Qt环境中如何使用QSQLITE驱动创建SQLite数据库文件(info.db),建立student表,插入数据并进行查询操作。通过QSqlDatabase、QSqlQuery等类完成数据库的连接、错误处理、表创建、批处理插入及数据检索。
摘要由CSDN通过智能技术生成

测试QSQLITE:

先要创建db文件:

 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();
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值