Connect and use SQLite3 database in QT

Table of contents

1. Add the database module to the project

 2. Add database-related header files

3. Connect and open the database

4. Database operation, query data in the table

1. Add the database module to the project

Add sql to the .pro file of the QT project.

 2. Add database-related header files

#include <QSqlDatabase>    // Qt 框架中用于连接数据库的类
#include <QSqlQuery>       //Qt 框架中用于处理 SQL 语句的类是一个查询执行器,它可以接受 SQL 查询语句并返回查询结果。

3. Connect and open the database

QSqlDatabase db = QSqlDatabase :: addDatabase("QSQLITE");    //创建数据库连接
db.setDatabaseName("class.db");    //设置连接的数据库的名称
db.open();                    //打开数据库
if (!db.isOpen())
{
    qDebug() << "数据库连接失败:" ;
}

After opening the database for the first time, if the database is still used in other places later, there is no need to reconnect at this time. First check whether the project is connected to the database, if not, create a connection, and if it has been connected, there is no need to reconnect. The detection code is as follows:

QSqlDatabase db;
    if(QSqlDatabase::contains("qt_sql_default_connection"))
      db = QSqlDatabase::database("qt_sql_default_connection");
    else
      db = QSqlDatabase::addDatabase("QSQLITE");

4. Database operation, query data in the table

Find a table named seattab in the database.

This code uses the QSqlQuery class to query the database and a while loop to iterate through the query results.

In each loop, the query.next() method returns true, indicating that the current record has been read. Then, we can use the query.value("accont") or query.value(0) method to get the value of the specified column in the table.

Here, we use "account", "name" and "seatnum" to specify the column names to fetch. The toInt() method converts the returned value of the specified column into an integer type, and the toString() method converts the returned value of the specified column into a string type.

QString tableName = "seattab";
QSqlQuery query;
query.exec(QString("select * from %1").arg(tableName));
while(query.next())
    {
        int accounts = query.value("account").toInt();
        QString names = query.value("name").toString();
        QString seatnums = query.value("seatnum").toString();

        //或者使用列数来获取表中的值
        int accounts = query.value(0).toInt();
        QString names = query.value(1).toString();
        QString seatnums = query.value(2).toString();

        qDebug()<<accounts;
        qDebug()<<names;
        qDebug()<<seatnums;
    }   
db.close();    //关闭数据库

Guess you like

Origin blog.csdn.net/weixin_55735677/article/details/130198852