QT+SQLite3 基础

前端之家收集整理的这篇文章主要介绍了QT+SQLite3 基础前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

环境:DebianGNU/Linux8.1

QT版本:Qt Creator 3.2.1 Based on Qt 5.3.2(GCC 4.9.2,32bit)

sqlite可视化软件:sqlitebrowser


.pro文件加上

QT += sql

文件
#include<Qtsql>

(1)建数据库、建表、插入数据、读取数据
    QsqlDatabase db = QsqlDatabase::addDatabase("QsqlITE");
    db.setDatabaseName("DB.db");
    if(!db.open())
    {
        qDebug() << "database open Failed!";
        return ;
    }


    QsqlQuery query;

    query.exec("create table student(id varchar,name varchar)");
    query.exec(QObject::tr("insert into student values(1,'Rachel')"));
    query.exec(QObject::tr("insert into student values(2,'Phoebe')"));
    query.exec(QObject::tr("insert into student values(3,'Monica')"));
    query.exec(QObject::tr("insert into student values(4,'Chandler')"));
    query.exec(QObject::tr("insert into student values(5,'张三')"));
    query.exec(QObject::tr("insert into student values(6,'李四')"));
    query.exec(QObject::tr("insert into student values(7,'王五')"));
    query.exec(QObject::tr("insert into student values(8,'赵四')"));
    query.exec(QObject::tr("insert into student values(9,'赵五')"));
    query.exec(QObject::tr("insert into student values(10,'赵六')"));

    query.exec("select id,name from student where id>=1");
    while(query.next())
    {
        int ele0=query.value(0).toInt();
        QString ele1 = query.value(1).toString();
        qDebug() << ele0 << " " << ele1;
    }

(2)建数据库、建表(主键自增)、插入数据、读取数据

    QsqlDatabase db = QsqlDatabase::addDatabase("QsqlITE");
    db.setDatabaseName("DB.db");
    if(!db.open())
    {
        qDebug() << "database open Failed!";
        return ;
    }


    QsqlQuery query;

    query.exec("create table student(id INTEGER PRIMARY KEY AUTOINCREMENT,name TEXT NOT NULL)");
    query.exec(QObject::tr("insert into student values(NULL,'Rachel')"));
    query.exec(QObject::tr("insert into student values(NULL,'Phoebe')"));
    query.exec(QObject::tr("insert into student values(NULL,'Monica')"));
    query.exec(QObject::tr("insert into student values(NULL,'Chandler')"));
    query.exec(QObject::tr("insert into student values(NULL,'张三')"));
    query.exec(QObject::tr("insert into student values(NULL,'李四')"));
    query.exec(QObject::tr("insert into student values(NULL,'王五')"));
    query.exec(QObject::tr("insert into student values(NULL,'赵四')"));
    query.exec(QObject::tr("insert into student values(NULL,'赵五')"));
    query.exec(QObject::tr("insert into student values(NULL,name from student where id>=1");
    while(query.next())
    {
        int ele0=query.value(0).toInt();
        QString ele1 = query.value(1).toString();
        qDebug() << ele0 << " " << ele1;
    }
原文链接:https://www.f2er.com/sqlite/198828.html

猜你在找的Sqlite相关文章