Qt SQLite database operations

Projects typically require the use of various databases (such as Qracle, SQL Server, MySQL, etc.) to achieve the storage of data, query and other functions. The following explains how to operate SQlite database in Qt.


A, SQLite Introduction

A lightweight database Sqlite database frequently used as a Qt project development, arguably one of the relatively good database compatibility (Sqlite like Qt's own son, the same as Microsoft Access compatible database). Above Qt5 version can be used directly (Qt comes with the drive), it is a lightweight database, profiles up has the following advantages:

  • Designed to SQLite is an embedded SQL database engine, which is based on pure C language code, it has been used in a very wide range of areas.
  • SQLite when you need long term storage can read the data file (.db) on the hard disk, no need for a long time in the memory can also be placed in the entire database in memory, both of which do not require additional server-side process, namely SQLite the database engine is no need to run independently.
  • Source code open source, you can be used for any purpose, including selling it.
  • Zero-configuration - no need to install and manage configuration.
  • It requires no configuration, no installation and does not require administrator.
  • The same data file can be used on different machines, may be freely shared among different byte order machines.
  • Support for multiple programming languages, C, C ++, PHP, Perl, Java, C #, Python, Ruby and so on.


Second, the use of

2.1 Preparation

1, the introduction of SQL module
in Qt project file (.pro file), by adding SQL module:

QT += sql


2, reference header files

In the class definition requires the use of SQL, reference the relevant header files. E.g:

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


2.2

1, to establish a database

QSqlDatabase database;

if (QSqlDatabase::contains("qt_sql_default_connection"))
{
    database = QSqlDatabase::database("qt_sql_default_connection");
}
else
{
    // 建立和SQlite数据库的连接
    database = QSqlDatabase::addDatabase("QSQLITE");
    // 设置数据库文件的名字
    database.setDatabaseName("MyDataBase.db");
}
  • The first line, the establishment of a QSqlDatabasetarget, a subsequent operation to use the object.

  • ifStatement is used to check the specified connection (Connection) exists. Connection name (connection name) is specified here qt_sql_default_connection, which is the default Qt connection name. Actual use, this name can be arbitrarily taken. If it is determined in this connection already exists, then the QSqlDatabase::contains()function returns true. In this case, into the first branch, QSqlDatabase::database()it returns the connection.

  • If the connection does not exist, then enter the elsebranch, to establish the connection, and add the database. In the elsebranch of the first line, addDatabase()the parameters of QSQLITEa corresponding drive SQLite name can not be changed. Also note that the addDatabase()second parameter is omitted, the default parameters of the second parameter Qt is the above-mentioned default connection name qt_sql_default_connection. If you need to use custom connection name (if the program requires a plurality of database files, then the processing will be the case), you should add a second parameter, for example:

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

    This time, in another place if needed to determine my_sql_connectionwhether the connection exists, it should be used if (QSqlDatabase::contains("my_sql_connection")).

  • elseThe second line branch, the setDatabaseName()parameter is the database file name. If the database does not exist, it is automatically created when a subsequent operation; if it already exists, subsequent operation will be carried out on the existing database.


2, open the database

Use open()open the database and determine success. Note that in the first step to check whether there is connection, if the connection exists, then return this connection, when the default database is opened.

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

If you open the database is successful, the else branch. Operation of the database need to be in the else branch.


3, close the database

After the completion of database operations, the best closed.

database.close();


4, operation of the database

Operation of the database need to use the QSqlQueryclass, you must define an object before the operation. The following illustrates a method of operation. Operation requires the use of SQL statements, a few examples in this article will use several common statement, specific information on SQL statement can refer to my other blog post: [ SQL must know will be] study notes .


Example 1: Create a table

Create a table named student of the table contains three columns, the first column is the id, the second column is the name of the third column is age.

// 用于执行sql语句的对象
QSqlQuery sqlQuery;
// 构建创建数据库的sql语句字符串
QString createSql = QString("CREATE TABLE STUDENT (\
                          ID INT PRIMARY KEY NOT NULL,\
                          NAME TEXT NOT NULL,\
                          AGE INT NOT NULL)");
sqlQuery.prepare(createSql);
// 执行sql语句
if(!sqlQuery.exec())
{
    qDebug() << "Error: Fail to create table. " << sqlQuery.lastError();
}
else
{     qDebug() << "Table created!";
}
  • The first line defines an QSqlQueryobject.

  • The second line is QStringwhere the content is SQLite statement. Operation of the database, are used SQLite statement completed, these instructions QString type, by preparefunction, stored in QSqlQuery object. It may also be instructions to write directly form QString exec()function parameters, for example:

    sql_query.exec("CREATE TABLE STUDENT (ID INT PRIMARY KEY NOT NULL, ...)");
  • If sql_query.exec()executed successfully, create a table success.


Example 2: inserting a single row of data

In the table you just created, insert a single row of data.

// 方法一:使用 bindValue 函数插入单行数据
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 函数插入单行数据
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 
}


Example 3: Query all data

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);
}
}


Example 4: update data (modification data)

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!";
}


Third, the complete sample program

The above name just a few examples of common SQL statement, a complete sample posted following procedure:

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();

    // 打开数据库
    bool openDb(void);
    // 创建数据表
    void createTable(void);
    // 判断数据表是否存在
    bool isTableExist(QString& Tabname);
    // 查询全部数据
    void queryTable();
    // 插入数据
    void singleInsertData(w2dba &singledb); // 插入单条数据
    void moreInsertData(QList<w2dba> &moredb); // 插入多条数据
    // 修改数据
    void modifyData(int id, QString name, int age);
    // 删除数据
    void deleteData(int id);
    //删除数据表
    void deleteTable(QString& tableName);
    // 关闭数据库
    void closeDb(void);

private:
    QSqlDatabase database;// 用于建立和数据库的连接
};

#endif //  SQLITEOPERATOR_H


SqliteOperator.cpp

#include "sqliteoperator.h"

// 构造函数中初始化数据库对象,并建立数据库
SqliteOperator::SqliteOperator()
{
    if (QSqlDatabase::contains("qt_sql_default_connection"))
    {
        database = QSqlDatabase::database("qt_sql_default_connection");
    }
    else
    {
        // 建立和SQlite数据库的连接
        database = QSqlDatabase::addDatabase("QSQLITE");
        // 设置数据库文件的名字
        database.setDatabaseName("MyDataBase.db");
    }
}

// 打开数据库
bool SqliteOperator::openDb()
{
    if (!database.open())
    {
        qDebug() << "Error: Failed to connect database." << database.lastError();
    }
    else
    {
        // do something
    }

    return true;
}

// 创建数据表
void SqliteOperator::createTable()
{
    // 用于执行sql语句的对象
    QSqlQuery sqlQuery;
    // 构建创建数据库的sql语句字符串
    QString createSql = QString("CREATE TABLE STUDENT (\
                          ID INT PRIMARY KEY NOT NULL,\
                          NAME TEXT NOT NULL,\
                          AGE INT NOT NULL)");
    sqlQuery.prepare(createSql);
    // 执行sql语句
    if(!sqlQuery.exec())
    {
        qDebug() << "Error: Fail to create table. " << sqlQuery.lastError();
    }
    else
    {
        qDebug() << "Table created!";
    }
}

// 判断数据库中某个数据表是否存在
bool SqliteOperator::isTableExist(QString& tableName)
{
    QSqlDatabase db = QSqlDatabase::database();
    if(db.tables().contains(tableName))
    {
        return true;
    }

    return false;
}

// 查询全部数据
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);
        }
    }
}

// 插入单条数据
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
    }
}

// 插入多条数据
void SqliteOperator::moreInsertData(QList<w2dba>& moredb)
{
    // 进行多个数据的插入时,可以利用绑定进行批处理
    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();
    }
}

// 修改数据
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!";
    }
}

// 删除数据
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!";
    }
}

//删除数据表
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);

    //创建并打开SQLite数据库
    SqliteOperator sqlTest;
    sqlTest.openDb();

    // 创建数据表
    sqlTest.createTable();

    // 判断数据表是否存在
    QString str1 = QString("STUDENT");
    qDebug() << "isTabelExist:" <<sqlTest.isTableExist(str1);

    // 插入单条数据
    w2dba w2dbaTest1 = {1, "zhangSan", 24};
    w2dba w2dbaTest2 = {2, "lisi", 28};
    sqlTest.singleInsertData(w2dbaTest1);
    sqlTest.singleInsertData(w2dbaTest2);

    // 插入多条数据
    QList<w2dba> list;
    w2dba w2dbaTest3 = {3, "liwu", 26};
    w2dba w2dbaTest4 = {4, "niuer", 27};
    list.append(w2dbaTest3);
    list.append(w2dbaTest4);
    sqlTest.moreInsertData(list);
    // 查询全部数据
    sqlTest.queryTable();
    qDebug() << endl;

    // 修改数据
    sqlTest.modifyData(2, "modify", 10);
    // 查询全部数据
    sqlTest.queryTable();
    qDebug() << endl;

    // 删除数据
    sqlTest.deleteData(2);
    // 查询全部数据
    sqlTest.queryTable();
    qDebug() << endl;

    // 删除数据表
    QString str2 = QString("STUDENT");
    sqlTest.deleteTable(str2);

    //关闭数据库
    sqlTest.closeDb();

    return a.exec();
}


Results are as follows:

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


reference:

Qt operating Sqlite database (1)

QT5 use SQLite

Use SQLite database in Qt


Guess you like

Origin www.cnblogs.com/linuxAndMcu/p/11364071.html