Talking about the Application of Qt in Sqlite

1. Introduction to Sqlite

        SQLite is a lightweight database, a relational database management system that complies with ACID , and it is a relatively small database. Its design direction is embedded , and it has been applied in many embedded products . It occupies very low resources. In embedded devices , it may occupy hundreds of kb of memory. At the same time, it supports mainstream operating systems such as Windows/Linux/Unix, and can be combined with many programming languages, such as C ++, C#, PHP, Java, etc., and has an ODBC interface. In terms of processing speed, it is faster than them all.

Second, the application in Qt

1. Introduce the sql module into the Qt project

   Add Qt += sql to the project pro file

2. Add the header file

#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlError>
#include <QDebug>
#include <QList>

3. Open and close the database

1) Open the database

QSqlDatabase db;QList<QString> g_tbNameList;
QStringList g_recordList;

bool openDB()
{
    db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName("client.db");
    
    bool ok = m_db.open();
    retun ok;
}

2) Close the database

void closeDB()
{
    if(db.isOpen())
        db.close();
}

4. Check how many tables and table names there are in the database

bool checkDBTableName()
{
    bool bSuccess = false;
    if(openDB())
    {
        QStringList tableList = m_db.tables();
        //表个数
        int tbCount = tableList.count();
        QString sTableName;
        foreach (sTableName, tableList) 
        {
            g_tbNameList.append(sTableName);
        }
        if(g_tbNameList.size() > 0)
        {
            bSuccess = true;
        }
    }
    closeDB();
    
    return bSuccess;
}

5. Check the field names in the database table

void checkDBRecord(QString sDBTableName)
{
    if(openDB())
    {
        QSqlQuery query;
        QString sql = QString("select * from %1").arg(sDBTableName);
        if(!query.exec(sql))
        {
            qDebug()<<query.lastError().databaseText();
        }

        if(query.numRowsAffected() != 0)
        {
            while(query.next())
            {
                for(int i = 0; i<query.record().count(); i++)
                {
                    g_recordList<<query.record().fieldName(i);
                }
            }
        }

    }
    closeDB();
}

6. Check if there is a record in the data table

bool checkDBTableSpecificName(QString sDBTableName)
{
    bool bSuccess = false;
    if(openDB())
    {
        QSqlQuery query;
        QString sql = QString("select count(*) from sqlite_master where type='table' and name='%1';").arg(sDBTableName);
        if(!query.exec(sql))
        {
            qDebug()<<query.lastError().databaseText();
        }

        if(query.numRowsAffected() != 0)
        {             if(query.next())             {                  if(query.value(0).toInt()==0)                 {                     // table absent                     bSuccess = true;                 }else{                     // table exists                     bSuccess = false;                 }             }         }     }     closeDB();     return bSuccess ;















7. Qt scheme for extracting table data

bool selectDBTableData(QString sDBTableName)
{
    bool bSuccess = false;
    if(openDB())
    {
        QSqlQuery query;
        QString sql = QString("select * from %1").arg(sDBTableName);
        if(!query.exec(sql))
        {
            qDebug()<<query.lastError().text();
        }

        if(query.numRowsAffected() != 0)
        {
            while(query.next())
            {
                //方案一:
                QString sName      = query.value(0).toString();
                int num          = query.value(1).toInt();
                double dMoneyNum = query.value(2).toDouble();
                bool    bRun     = query.value(3).toBool();
                
                //方案二:
                QString sName      = query.value("ID").toString();
                int num          = query.value("Num").toInt();
                double dMoneyNum = query.value("MoneyNum").toDouble();
                bool    bRun     = query.value("Run").toBool();
                //方案三:
                QString sName      = query.record().value(0).toString();
                int num          = query.record().value(1).toInt();
                double dMoneyNum = query.record().value(2).toDouble();
                bool    bRun     = query.record().value(3).toBool();
                //方案四:
                QString sName      = query.record().value("ID").toString();
                int num          = query.record().value("Num").toInt();
                double dMoneyNum = query.record().value("MoneyNum").toDouble();
                bool    bRun     = query.record().value("Run").toBool();
            }
        }

    }
    closeDB();
    return bSuccess;
}

8. Data table insert data

bool insertDBTableAllRecord(QString sDBTableName, QString sName, int num, double dMoneyNum, bool bRun)
{
    bool bSuccess = false;
    if(openDB())
    {
        //方案一:
        QSqlQuery query;
        QString sql = QString("insert into '%1' (Name, num, MoneyNum, Run) values('%2', %3, %4, %5)").arg(sDBTableName).arg(sName).arg(num).arg(dMoneyNum).arg(bRun);
        if(!query.exec(sql))
        {
            qDebug()<<query.lastError().text();
        }
        else
        {
            bSuccess = true;
        }
        //方案二:
        QString sql = QString("insert into '%1' (Name, num, MoneyNum, Run) values (:Name, :num, :MoneyNum, :Run)").arg(sDBTableName);
        QSqlQuery query;
        query.prepare(sql);
        query.bindValue(":Name", "Tom");
        query.bindValue(":Num", 25);
        query.bindValue(":MoneyNum", 160.8995);
        query.bindValue(":Run", 1);
        if(!query.exec(sql))
        {
            qDebug()<<query.lastError().text();
        }
        else
        {
            bSuccess = true;
        }
        //方案三:
        QString sql = QString("insert into '%1' (Name, num, MoneyNum, Run) values (:ID, :Num, :MoneyNum, :Run)").arg(sDBTableName);
        QSqlQuery query;
        query.prepare(sql);
        query.bindValue(0, "Tom");
        query.bindValue(1, 25);
        query.bindValue(2, 160.8995);
        query.bindValue(3, 1);
        if(!query.exec(sql))
        {
            qDebug()<<query.lastError().text();
        }
        else
        {
            bSuccess = true;
        }
        //方案四:
        QString sql = QString("insert into '%1' (Name, num, MoneyNum, Run) values (?, ?, ?, ?)").arg(sDBTableName);
        QSqlQuery query;
        query.prepare(sql);
        query.addBindValue("Tom");
        query.addBindValue(25);
        query.addBindValue(160.8995);
        query.addBindValue(1);
        if(!query.exec(sql))
        {
            qDebug()<<query.lastError().text();
        }
        else
        {
            bSuccess = true;
        }

    }
    closeDB();
    return bSuccess;
}

9. Delete the specified record in the table

bool deleteDBTableAllRecord(QString sName)
{
    bool bSuccess = false;
    if(openDB())
    {
        QSqlQuery query;
        QString sql = QString("delete * from %1 where Name = '%2'").arg(sDBTableName).arg(sName);
        if(!query.exec(sql))
        {
            qDebug()<<query.lastError().text();
        }
        else
        {
            bSuccess = true;
        }
    }
    closeDB();
    return bSuccess;
}

10. Update table records

bool updateDBTableRecord(QString sName)
{
    bool bSuccess = false;
    if(openDB())
    {
        QSqlQuery query;
        QString sql = QString("update %1 set Name = '%2'").arg(sDBTableName).arg(sName);
        if(!query.exec(sql))
        {
            qDebug()<<query.lastError().text();
        }
        else
        {
            bSuccess = true;
        }
    }
    closeDB();
    return bSuccess;
}

11. About the transaction in the Qt database sqlite

SQLite
starts the transaction: "begin;";
rolls back: "rollback;";
commits the transaction: "commit;".

QSqlDatabase provides corresponding transaction, rollback, and commit three functions to perform corresponding operations.

1) Detect whether transactions are supported:

qDebug() <<"DB hasFeature:Transaction:" <<db.driver()->hasFeature(QSqlDriver::Transactions);

2) Example 1:

bool updateDBTableRecord(QString sName)
{
    bool bSuccess = false;
    if(openDB())
    {
        QSqlQuery query;
        QString sql = QString("update %1 set Name = '%2'").arg(sDBTableName).arg(sName);
        if(!query.exec(sql))
        {
            qDebug()<<query.lastError().text();
            query.exec("ROLLBACK");//提交
        }
        else
        {
            bSuccess = true;
            query.exec("COMMIT");//提交
        }
    }
    closeDB();
    return bSuccess;
}

Example 2:

bool insertDBTableAllRecord(QString sDBTableName, QString sName, int num, double dMoneyNum, bool bRun)
{
    bool bSuccess = false;
    db.transaction();
    if(openDB())
    {
        QSqlQuery query;
        QString sql = QString("insert into '%1' (Name, num, MoneyNum, Run) values('%2', %3, %4, %5)").arg(sDBTableName).arg(sName).arg(num).arg(dMoneyNum).arg(bRun);
        if(!query.exec(sql))
        {
            qDebug()<<query.lastError().text();
        }
        else
        {
            bSuccess = true;
        }
    }
    m_db.commit();
    closeDB();
    return bSuccess;
}
Description: Using transactions can improve the read and write efficiency of the database, and secondly ensure the security of the data. It has the characteristics of atomicity (Atomicity), consistency (Consistency), isolation (Isolation) and persistence (Durability).

Guess you like

Origin blog.csdn.net/leiyang2014/article/details/125821128