[Qt first entered the rivers and lakes] Qt QSqlDatabase underlying architecture and principle detailed description

Yuxian: CSDN content partner, CSDN new star mentor, full-stack creative star creator, 51CTO (Top celebrity + expert blogger), github open source enthusiast (go-zero source code secondary development, game back-end architecture https: https://github.com/Peakchen)

 

Qt QSqlDatabase is a class used in Qt to implement database connection and data operation. It supports a variety of database systems, including MySQL, PostgreSQL, SQLite, Oracle, etc. In this article, we will introduce the underlying architecture, principles and implementation methods of Qt QSqlDatabase in detail.

The underlying architecture of Qt QSqlDatabase consists of the following parts:

  1. Qt SQL Drivers

Qt SQL Drivers is a driver used in Qt to realize database connection and data operation, and it supports a variety of database systems. In Qt, each database system corresponds to a Qt SQL Driver, and each Qt SQL Driver is a dynamic link library (DLL).

  1. QSqlDatabase

QSqlDatabase is a class used in Qt to implement database connection and data operation. It can connect to different database systems and provide a series of methods for operating databases. Before using QSqlDatabase, you need to load the corresponding Qt SQL Driver.

  1. QSqlQuery

QSqlQuery is a class used to implement SQL queries in Qt, it can execute SQL statements, and store the results in QSqlQuery objects for subsequent processing.

The following is the underlying architecture diagram of the QSqlDatabase class:

+-----------------+
|   QSqlDatabase  |
+-----------------+
| - driver        |
| - hostName      |
| - databaseName  |
| - userName      |
| - password      |
| - port          |
| - options       |
+-----------------+
          /_\
           |
           | 继承
           |
+-----------------+
|   QSqlDriver    |
+-----------------+
| - db            |
+-----------------+
          /_\
           |
           | 实例化
           |
+-----------------+
|   QSqlDatabase  |
+-----------------+

In this architecture, the QSqlDatabase class is an abstraction of a database connection, which includes the driver, host name, database name, user name, password, port number and other options related to the connection. The QSqlDriver class is an abstract class that defines a set of pure virtual functions for connecting and operating databases, which need to be implemented by each database driver. When the QSqlDatabase class is instantiated, a corresponding QSqlDriver object will be created for actual connection and operation of the database.

In Qt, we can use the following methods to implement database connection and data manipulation:

  1. QSqlDatabase::addDatabase()

The addDatabase() method is used to add a database connection, which accepts a parameter of type string, indicating the name of the database system to be connected. For example:

QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
  1. QSqlDatabase::setHostName()、QSqlDatabase::setDatabaseName()、QSqlDatabase::setUserName()、QSqlDatabase::setPassword()

These methods are used to set the hostname, databasename, username and password for the database connection. For example:

db.setHostName("localhost");
db.setDatabaseName("mydatabase");
db.setUserName("myusername");
db.setPassword("mypassword");
  1. QSqlDatabase::open()

The open() method is used to open the database connection. If the connection is successful, it returns true, otherwise it returns false. For example:

if (db.open()) {
    qInfo() << "Database connection opened";
} else {
    qWarning() << "Failed to open database connection:" << db.lastError().text();
}
  1. QSqlQuery::exec()

The exec() method is used to execute the SQL statement and store the result in the QSqlQuery object. For example:

QSqlQuery query;
if (query.exec("SELECT * FROM mytable")) {
    while (query.next()) {
        QString name = query.value("name").toString();
        int age = query.value("age").toInt();
        // 处理查询结果
    }
} else {
    qWarning() << "Failed to execute SQL statement:" << query.lastError().text();
}
  1. QSqlQuery::bindValue()

The bindValue() method is used to set the parameter value in the SQL statement. For example:

QSqlQuery query;
query.prepare("SELECT * FROM mytable WHERE name = ?");
query.bindValue(0, "John");
if (query.exec()) {
    while (query.next()) {
        // 处理查询结果
    }
} else {
    qWarning() << "Failed to execute SQL statement:" << query.lastError().text();
}
  1. QSqlQuery::lastInsertId()

The lastInsertId() method is used to obtain the auto-increment ID generated by the last insert operation. For example:

QSqlQuery query;
query.prepare("INSERT INTO mytable (name, age) VALUES (?, ?)");
query.bindValue(0, "John");
query.bindValue(1, 30);
if (query.exec()) {
    int id = query.lastInsertId().toInt();
    qInfo() << "Inserted record with id:" << id;
} else {
    qWarning() << "Failed to execute SQL statement:" << query.lastError().text();
}

The following is a simple Qt QSqlDatabase implementation example, which includes the use of the above methods:

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

int main(int argc, char *argv[])
{
    QCoreApplication app(argc, argv);

    // 添加MySQL数据库连接
    QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
    db.setHostName("localhost");
    db.setDatabaseName("mydatabase");
    db.setUserName("myusername");
    db.setPassword("mypassword");

    // 打开数据库连接
    if (db.open()) {
        qInfo() << "Database connection opened";

        // 执行SQL查询
        QSqlQuery query;
        if (query.exec("SELECT * FROM mytable")) {
            while (query.next()) {
                QString name = query.value("name").toString();
                int age = query.value("age").toInt();
                qInfo() << "Name:" << name << "Age:" << age;
            }
        } else {
            qWarning() << "Failed to execute SQL statement:" << query.lastError().text();
        }

        // 执行SQL插入操作
        query.prepare("INSERT INTO mytable (name, age) VALUES (?, ?)");
        query.bindValue(0, "John");
        query.bindValue(1, 30);
        if (query.exec()) {
            int id = query.lastInsertId().toInt();
            qInfo() << "Inserted record with id:" << id;
        } else {
            qWarning() << "Failed to execute SQL statement:" << query.lastError().text();
        }

        // 关闭数据库连接
        db.close();
        qInfo() << "Database connection closed";
    } else {
        qWarning() << "Failed to open database connection:" << db.lastError().text();
    }

    return app.exec();
}

In the above example, we first use the addDatabase() method to add a MySQL database connection and set the connection information. Then use the open () method to open the database connection, and perform a SQL query and a SQL insert operation. Finally, the database connection is closed using the close() method.

Qt QSqlDatabase provides a convenient way to connect and operate databases, and its underlying architecture and implementation methods are relatively simple and easy to understand. We only need to set the database connection information according to the above method, and then execute the SQL statement to complete the database operation.

Guess you like

Origin blog.csdn.net/feng1790291543/article/details/131807449