QT5中如何使用SQLite

导读 SQLite是一款开源轻量级的数据库软件,本文主要介绍了QT5中使用SQLite的实现方法,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

SQLite(sql)是一款开源轻量级的数据库软件,不需要server,可以集成在其他软件中,非常适合嵌入式系统。
Qt5以上版本可以直接使用SQLite。

1、修改.pro文件,添加SQL模块:
QT += sql
2、main.cpp代码如下:
#include "mainwindow.h"
#include 
//添加头文件
#include 
#include 
#include 
#include 
 
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
 
    //建立并打开数据库
    QSqlDatabase database;
    database = QSqlDatabase::addDatabase("QSQLITE");
    database.setDatabaseName("MyDataBase.db");
    if (!database.open())
    {
        qDebug() << "Error: Failed to connect database." << database.lastError();
    }
    else
    {
        qDebug() << "Succeed to connect database." ;
    }
 
    //创建表格
    QSqlQuery sql_query;
    if(!sql_query.exec("create table student(id int primary key, name text, age int)"))
    {
        qDebug() << "Error: Fail to create table."<< sql_query.lastError();
    }
    else
    {
        qDebug() << "Table created!";
    }
 
    //插入数据
    if(!sql_query.exec("INSERT INTO student VALUES(1, \"Wang\", 23)"))
    {
        qDebug() << sql_query.lastError();
    }
    else
    {
        qDebug() << "inserted Wang!";
    }
    if(!sql_query.exec("INSERT INTO student VALUES(2, \"Li\", 23)"))
    {
        qDebug() << sql_query.lastError();
    }
    else
    {
        qDebug() << "inserted Li!";
    }
 
    //修改数据
    sql_query.exec("update student set name = \"QT\" where id = 1");
    if(!sql_query.exec())
    {
        qDebug() << sql_query.lastError();
    }
    else
    {
        qDebug() << "updated!";
    }
 
    //查询数据
    sql_query.exec("select * from student");
    if(!sql_query.exec())
    {
        qDebug()<
3、应用程序输出如下:

QT5中如何使用SQLite

4、创建的 MyDataBase.db 在build的这个文件夹下:

D:\QT\project\build-sl-Desktop_Qt_5_10_1_MinGW_32bit-Debug

原文来自:https://www.jb51.net/article/230477.htm

本文地址:https://www.linuxprobe.com/qt5-sqlite-method.html编辑:倪家兴,审核员:逄增宝

Linux命令大全:https://www.linuxcool.com/

© 版权声明
THE END
喜欢就支持一下吧