溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Qt怎么操作SQLite數(shù)據(jù)庫

發(fā)布時間:2023-03-10 10:55:45 來源:億速云 閱讀:109 作者:iii 欄目:開發(fā)技術

今天小編給大家分享一下Qt怎么操作SQLite數(shù)據(jù)庫的相關知識點,內容詳細,邏輯清晰,相信大部分人都還太了解這方面的知識,所以分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后有所收獲,下面我們一起來了解一下吧。

1、SQLite 介紹

Sqlite 數(shù)據(jù)庫作為 Qt 項目開發(fā)中經常使用的一個輕量級的數(shù)據(jù)庫,可以說是兼容性相對比較好的數(shù)據(jù)庫之一(Sqlite就像Qt的親兒子,如同微軟兼容Access數(shù)據(jù)庫一樣)。Qt5 以上版本可以直接使用(Qt自帶驅動),是一個輕量級的數(shù)據(jù)庫,概況起來具有以下優(yōu)點:

  • SQLite 的設計目的是嵌入式 SQL 數(shù)據(jù)庫引擎,它基于純C語言代碼,已經應用于非常廣泛的領域內。

  • SQLite 在需要長時間存儲時可以直接讀取硬盤上的數(shù)據(jù)文件(.db),在無須長時間存儲時也可以將整個數(shù)據(jù)庫置于內存中,兩者均不需要額外的服務器端進程,即 SQLite 是無須獨立運行的數(shù)據(jù)庫引擎。

  • 源代碼開源,你可以用于任何用途,包括出售它。

  • 零配置 – 無需安裝和管理配置。

  • 不需要配置,不需要安裝,也不需要管理員。

  • 同一個數(shù)據(jù)文件可以在不同機器上使用,可以在不同字節(jié)序的機器間自由共享。

  • 支持多種開發(fā)語言,C, C++, PHP, Perl, Java, C#,Python, Ruby等。

2、用法

2.1、準備

1、引入SQL模塊

在Qt項目文件(.pro文件)中,加入SQL模塊:

QT += sql

2、引用頭文件

在需要使用SQL的類定義中,引用相關頭文件。例如:

#include <QSqlDatabase>
#include <QSqlError>
#include <QSqlQuery>

2.2、使用

1、建立數(shù)據(jù)庫

QSqlDatabase database;
 
if (QSqlDatabase::contains("qt_sql_default_connection"))
{
    database = QSqlDatabase::database("qt_sql_default_connection");
}
else
{
    // 建立和SQlite數(shù)據(jù)庫的連接
    database = QSqlDatabase::addDatabase("QSQLITE");
    // 設置數(shù)據(jù)庫文件的名字
    database.setDatabaseName("MyDataBase.db");
}

第一行中,建立了一個 QSqlDatabase 對象,后續(xù)的操作要使用這個對象。

if 語句用來檢查指定的連接(connection)是否存在。這里指定的連接名稱(connection name)是qt_sql_default_connection,這是 Qt 默認連接名稱。實際使用時,這個名稱可以任意取。如果判斷此連接已經存在,那么 QSqlDatabase::contains() 函數(shù)返回 true。此時,進入第一個分支,QSqlDatabase::database() 返回這個連接。

如果這個連接不存在,則進入else分支,需要創(chuàng)建連接,并添加數(shù)據(jù)庫。在else分支第一行,addDatabase()的參數(shù)QSQLITE是SQLite對應的驅動名,不能改。而且需要注意的是,addDatabase()的第二個參數(shù)被省略了,第二個參數(shù)的默認參數(shù)就是上面提到的Qt默認連接名稱 qt_sql_default_connection。如果需要使用自定義的連接名稱(如果程序需要處理多個數(shù)據(jù)庫文件的話就會這樣),則應該加入第二個參數(shù),例如:

database = QSqlDatabase::addDatabase("QSQLITE", "my_sql_connection);

這個時候,如果在另一個地方需要判斷my_sql_connection連接是否存在,就應該使用 if (QSqlDatabase::contains("my_sql_connection"))。

else 分支第二行中,setDatabaseName() 的參數(shù)是數(shù)據(jù)庫文件名。如果這個數(shù)據(jù)庫不存在,則會在后續(xù)操作時自動創(chuàng)建;如果已經存在,則后續(xù)的操作會在已有的數(shù)據(jù)庫上進行。

2、打開數(shù)據(jù)庫

使用 open() 打開數(shù)據(jù)庫,并判斷是否成功。注意,在第一步檢查連接是否存在時,如果連接存在,則在返回這個連接的時候,會默認將數(shù)據(jù)庫打開。

if (!database.open())
{
    qDebug() << "Error: Failed to connect database." << database.lastError();
}
else
{
    // do something
}

如果打開數(shù)據(jù)庫成功,則進入else分支。對數(shù)據(jù)庫的操作都需要在else分支中進行。

3、關閉數(shù)據(jù)庫

數(shù)據(jù)庫操作完成后,最好關閉。

database.close();

4、操作數(shù)據(jù)庫

對數(shù)據(jù)庫進行操作需要用到 QSqlQuery 類,操作前必須定義一個對象。下面舉例說明操作方法。

例1:創(chuàng)建表格

創(chuàng)建一個名為student的表格,表格包含三列,第一列是id,第二列是名字,第三列是年齡。

// 用于執(zhí)行sql語句的對象
QSqlQuery sqlQuery;
// 構建創(chuàng)建數(shù)據(jù)庫的sql語句字符串
QString createSql = QString("CREATE TABLE student (\
                          id INT PRIMARY KEY NOT NULL,\
                          name TEXT NOT NULL,\
                          age INT NOT NULL)");
sqlQuery.prepare(createSql);
// 執(zhí)行sql語句
if(!sqlQuery.exec())
{
    qDebug() << "Error: Fail to create table. " << sqlQuery.lastError();
}
else
{     qDebug() << "Table created!";
}

第一行定義一個 QSqlQuery 對象。

第二行是一個 QString,其中的內容是 SQLite 語句。對數(shù)據(jù)庫的操作,都是用 SQLite 的語句完成的,把這些指令以 QString 類型,通過 prepare 函數(shù),保存在 QSqlQuery 對象中。也可將指令,以 QString 形式直接寫在 exec() 函數(shù)的參數(shù)中,例如:

sql_query.exec("CREATE TABLE student (ID INT PRIMARY KEY NOT NULL, ...)");

如果 sql_query.exec() 執(zhí)行成功,則創(chuàng)建表格成功。

例2:插入單行數(shù)據(jù)

在剛才創(chuàng)建的表格中,插入單行數(shù)據(jù)。

// 方法一:使用 bindValue 函數(shù)插入單行數(shù)據(jù)
QSqlQuery sqlQuery;
sqlQuery.prepare("INSERT INTO student VALUES(:id,:name,:age)");
sqlQuery.bindValue(":id", max_id + 1);
sqlQuery.bindValue(":name", "Wang");
sqlQuery.bindValue(":age", 25);
if(!sqlQuery.exec())
{
    qDebug() << "Error: Fail to insert data. " << sqlQuery.lastError();
}
else
{
    // do something    
}
 
// 方法二:使用 addBindValue 函數(shù)插入單行數(shù)據(jù)
QSqlQuery sqlQuery;
sqlQuery.prepare("INSERT INTO student VALUES(?, ?, ?)");
sqlQuery.addBindValue(max_id + 1);
sqlQuery.addBindValue("Wang");
sqlQuery.addBindValue(25);
if(!sqlQuery.exec())
{
    qDebug() << "Error: Fail to insert data. " << sqlQuery.lastError();
}
else
{
    // do something    
}
 
// 方法三:直接寫出完整語句
if(!sql_query.exec("INSERT INTO student VALUES(3, \"Li\", 23)"))
{
    qDebug() << "Error: Fail to insert data. " << sqlQuery.lastError();
}
else
{
    // do something 
}

例3:查詢全部數(shù)據(jù)

QSqlQuery sqlQuery;
sqlQuery.exec("SELECT * FROM student");
if(!sqlQuery.exec())
{
    qDebug() << "Error: Fail to query table. " << sqlQuery.lastError();
}
else
{
    while(sqlQuery.next())
    {
        int id = sqlQuery.value(0).toInt();
        QString name = sqlQuery.value(1).toString();
        int age = sqlQuery.value(2).toInt();
        qDebug()<<QString("id:%1    name:%2    age:%3").arg(id).arg(name).arg(age);
    }
}

例4:更新數(shù)據(jù)(修改數(shù)據(jù))

QSqlQuery sqlQuery;
sqlQuery.prepare("UPDATE student SET name=?,age=? WHERE id=?");
sqlQuery.addBindValue(name);
sqlQuery.addBindValue(age);
sqlQuery.addBindValue(id);
if(!sqlQuery.exec())
{
    qDebug() << sqlQuery.lastError();
}
else
{
    qDebug() << "updated data success!";
}

3、完整示例程序

上面只是列舉了幾個常用的SQL語句例子,下面貼出一個完整示例程序:

SqliteOperator.h

#ifndef SQLITEOPERATOR_H
#define SQLITEOPERATOR_H
 
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlError>
#include <QDebug>
 
typedef struct
{
    int id;
    QString name;
    int age;
}w2dba;
 
class SqliteOperator
{
public:
    SqliteOperator();
 
    // 打開數(shù)據(jù)庫
    bool openDb(void);
    // 創(chuàng)建數(shù)據(jù)表
    void createTable(void);
    // 判斷數(shù)據(jù)表是否存在
    bool isTableExist(QString& tableName);
    // 查詢全部數(shù)據(jù)
    void queryTable();
    // 插入數(shù)據(jù)
    void singleInsertData(w2dba &singleData); // 插入單條數(shù)據(jù)
    void moreInsertData(QList<w2dba> &moreData); // 插入多條數(shù)據(jù)
    // 修改數(shù)據(jù)
    void modifyData(int id, QString name, int age);
    // 刪除數(shù)據(jù)
    void deleteData(int id);
    //刪除數(shù)據(jù)表
    void deleteTable(QString& tableName);
    // 關閉數(shù)據(jù)庫
    void closeDb(void);
 
private:
    QSqlDatabase database;// 用于建立和數(shù)據(jù)庫的連接
};
 
#endif //  SQLITEOPERATOR_H

SqliteOperator.cpp

#include "sqliteoperator.h"
 
// 構造函數(shù)中初始化數(shù)據(jù)庫對象,并建立數(shù)據(jù)庫
SqliteOperator::SqliteOperator()
{
    if (QSqlDatabase::contains("qt_sql_default_connection"))
    {
        database = QSqlDatabase::database("qt_sql_default_connection");
    }
    else
    {
        // 建立和SQlite數(shù)據(jù)庫的連接
        database = QSqlDatabase::addDatabase("QSQLITE");
        // 設置數(shù)據(jù)庫文件的名字
        database.setDatabaseName("MyDataBase.db");
    }
}
 
// 打開數(shù)據(jù)庫
bool SqliteOperator::openDb()
{
    if (!database.open())
    {
        qDebug() << "Error: Failed to connect database." << database.lastError();
    }
    else
    {
        // do something
    }
 
    return true;
}
 
// 創(chuàng)建數(shù)據(jù)表
void SqliteOperator::createTable()
{
    // 用于執(zhí)行sql語句的對象
    QSqlQuery sqlQuery;
    // 構建創(chuàng)建數(shù)據(jù)庫的sql語句字符串
    QString createSql = QString("CREATE TABLE student (\
                          id INT PRIMARY KEY NOT NULL,\
                          name TEXT NOT NULL,\
                          age INT NOT NULL)");
    sqlQuery.prepare(createSql);
    // 執(zhí)行sql語句
    if(!sqlQuery.exec())
    {
        qDebug() << "Error: Fail to create table. " << sqlQuery.lastError();
    }
    else
    {
        qDebug() << "Table created!";
    }
}
 
// 判斷數(shù)據(jù)庫中某個數(shù)據(jù)表是否存在
bool SqliteOperator::isTableExist(QString& tableName)
{
    QSqlDatabase database = QSqlDatabase::database();
    if(database.tables().contains(tableName))
    {
        return true;
    }
 
    return false;
}
 
// 查詢全部數(shù)據(jù)
void SqliteOperator::queryTable()
{
    QSqlQuery sqlQuery;
    sqlQuery.exec("SELECT * FROM student");
    if(!sqlQuery.exec())
    {
        qDebug() << "Error: Fail to query table. " << sqlQuery.lastError();
    }
    else
    {
        while(sqlQuery.next())
        {
            int id = sqlQuery.value(0).toInt();
            QString name = sqlQuery.value(1).toString();
            int age = sqlQuery.value(2).toInt();
            qDebug()<<QString("id:%1    name:%2    age:%3").arg(id).arg(name).arg(age);
        }
    }
}
 
// 插入單條數(shù)據(jù)
void SqliteOperator::singleInsertData(w2dba &singledb)
{
    QSqlQuery sqlQuery;
    sqlQuery.prepare("INSERT INTO student VALUES(:id,:name,:age)");
    sqlQuery.bindValue(":id", singledb.id);
    sqlQuery.bindValue(":name", singledb.name);
    sqlQuery.bindValue(":age", singledb.age);
    if(!sqlQuery.exec())
    {
        qDebug() << "Error: Fail to insert data. " << sqlQuery.lastError();
    }
    else
    {
        // do something
    }
}
 
// 插入多條數(shù)據(jù)
void SqliteOperator::moreInsertData(QList<w2dba>& moredb)
{
    // 進行多個數(shù)據(jù)的插入時,可以利用綁定進行批處理
    QSqlQuery sqlQuery;
    sqlQuery.prepare("INSERT INTO student VALUES(?,?,?)");
    QVariantList idList,nameList,ageList;
    for(int i=0; i< moredb.size(); i++)
    {
        idList <<  moredb.at(i).id;
        nameList << moredb.at(i).name;
        ageList << moredb.at(i).age;
    }
    sqlQuery.addBindValue(idList);
    sqlQuery.addBindValue(nameList);
    sqlQuery.addBindValue(ageList);
 
    if (!sqlQuery.execBatch()) // 進行批處理,如果出錯就輸出錯誤
    {
        qDebug() << sqlQuery.lastError();
    }
}
 
// 修改數(shù)據(jù)
void SqliteOperator::modifyData(int id, QString name, int age)
{
    QSqlQuery sqlQuery;
    sqlQuery.prepare("UPDATE student SET name=?,age=? WHERE id=?");
    sqlQuery.addBindValue(name);
    sqlQuery.addBindValue(age);
    sqlQuery.addBindValue(id);
    if(!sqlQuery.exec())
    {
        qDebug() << sqlQuery.lastError();
    }
    else
    {
        qDebug() << "updated data success!";
    }
}
 
// 刪除數(shù)據(jù)
void SqliteOperator::deleteData(int id)
{
    QSqlQuery sqlQuery;
 
    sqlQuery.exec(QString("DELETE FROM student WHERE id = %1").arg(id));
    if(!sqlQuery.exec())
    {
        qDebug()<<sqlQuery.lastError();
    }
    else
    {
        qDebug()<<"deleted data success!";
    }
}
 
//刪除數(shù)據(jù)表
void SqliteOperator::deleteTable(QString& tableName)
{
    QSqlQuery sqlQuery;
 
    sqlQuery.exec(QString("DROP TABLE %1").arg(tableName));
    if(sqlQuery.exec())
    {
        qDebug() << sqlQuery.lastError();
    }
    else
    {
        qDebug() << "deleted table success";
    }
}
 
void SqliteOperator::closeDb(void)
{
    database.close();
}

main.cpp

#include <QCoreApplication>
#include "sqliteoperator.h"
#include <QString>
 
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
 
    //創(chuàng)建并打開SQLite數(shù)據(jù)庫
    SqliteOperator sqlTest;
    sqlTest.openDb();
 
    // 創(chuàng)建數(shù)據(jù)表
    sqlTest.createTable();
 
    // 判斷數(shù)據(jù)表是否存在
    QString str1 = QString("student");
    qDebug() << "isTabelExist:" <<sqlTest.isTableExist(str1);
 
    // 插入單條數(shù)據(jù)
    w2dba w2dbaTest1 = {1, "zhangSan", 24};
    w2dba w2dbaTest2 = {2, "lisi", 28};
    sqlTest.singleInsertData(w2dbaTest1);
    sqlTest.singleInsertData(w2dbaTest2);
 
    // 插入多條數(shù)據(jù)
    QList<w2dba> list;
    w2dba w2dbaTest3 = {3, "liwu", 26};
    w2dba w2dbaTest4 = {4, "niuer", 27};
    list.append(w2dbaTest3);
    list.append(w2dbaTest4);
    sqlTest.moreInsertData(list);
    // 查詢全部數(shù)據(jù)
    sqlTest.queryTable();
    qDebug() << endl;
 
    // 修改數(shù)據(jù)
    sqlTest.modifyData(2, "modify", 10);
    // 查詢全部數(shù)據(jù)
    sqlTest.queryTable();
    qDebug() << endl;
 
    // 刪除數(shù)據(jù)
    sqlTest.deleteData(2);
    // 查詢全部數(shù)據(jù)
    sqlTest.queryTable();
    qDebug() << endl;
 
    // 刪除數(shù)據(jù)表
    QString str2 = QString("student");
    sqlTest.deleteTable(str2);
 
    //關閉數(shù)據(jù)庫
    sqlTest.closeDb();
 
    return a.exec();
}

運行結果如下:

Table created!
isTabelExist: true
"id:1    name:zhangSan    age:24"
"id:2    name:lisi    age:28"
"id:3    name:liwu    age:26"
"id:4    name:niuer    age:27"
 
updated data success!
"id:1    name:zhangSan    age:24"
"id:2    name:modify    age:10"
"id:3    name:liwu    age:26"
"id:4    name:niuer    age:27"
 
deleted data success!
"id:1    name:zhangSan    age:24"
"id:3    name:liwu    age:26"
"id:4    name:niuer    age:27"
 
deleted table success

以上就是“Qt怎么操作SQLite數(shù)據(jù)庫”這篇文章的所有內容,感謝各位的閱讀!相信大家閱讀完這篇文章都有很大的收獲,小編每天都會為大家更新不同的知識,如果還想學習更多的知識,請關注億速云行業(yè)資訊頻道。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經查實,將立刻刪除涉嫌侵權內容。

AI