34sqlite

sqlite,本地数据库。主要运用在小型的程序,传送方便(如发送附带数据库的程序,但MySQL有点大,或许没安装)。

如何创建本地数据库?

  1.新建一个.txt的文本文件。

  2.直接将后缀名有.txt改为.db即可。

  

思路和用法与前面的MySQL一样,连接上有点区别,其他一样。

1.连接数据库的类型不同

db=QSqlDatabase::addDatabase("QSQLITE");

2.Sqlite只需连接数据库,不需要设置数据库的地址,用户名,密码等

db.setDatabaseName("../student.db");

源代码:

#include "widget.h"

#include "ui_widget.h"

#include <QDebug>

#include<QtSql/QSqlDatabase>

#include <QSqlQuery>

#include <QVariantList>

Widget::Widget(QWidget *parent) :

    QWidget(parent),

    ui(new Ui::Widget)

{

    ui->setupUi(this);

    QSqlDatabase db;

    //查询qt支持的数据库驱动

    qDebug()<<QSqlDatabase::drivers();

    db=QSqlDatabase::addDatabase("QSQLITE");

   

    //连接数据库

    db.setDatabaseName("../student.db");

   

    //打开数据库

    if(!db.open())

    {

        return ;

    }

   

    //创建二维表

    QSqlQuery query;;

    query.exec("CREATE TABLE student(id INT PRIMARY KEY,sname VARCHAR(10),age INT,score INT)");

   

    //批量添加

    //预处理

    query.prepare("INSERT INTO student(id,sname,age,score) VALUES(:id,:sname,:age,:score)");

    //给字段设置内容

    QVariantList idList;

    idList<<1<<2<<3<<4;

    QVariantList snameList;

    snameList<<"小红"<<"小黑"<<"小白"<<"小华";

    QVariantList ageList;

    ageList<<15<<12<<23<<34;

    QVariantList scoreList;

    scoreList<<55<<66<<77<<88;

    //给字段绑定相应的值

    query.bindValue(":id",idList);

    query.bindValue(":sname",snameList);

    query.bindValue(":age",ageList);

    query.bindValue(":score",scoreList);

    //执行预处理命令

    query.execBatch();

    //显示数据

    query.exec("SELECT * FROM student");

    while(query.next())

    {

        qDebug()<<query.value("id").toInt()

                <<query.value("sname").toString()

                <<query.value("age").toInt()

                <<query.value("score").toInt();

    }

}

Widget::~Widget()

{

    delete ui;

}

结果图:

猜你喜欢

转载自www.cnblogs.com/gd-luojialin/p/9215876.html