T5中如何使用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中如何使用SQLiteQT5中如何使用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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章