QSqlDatabase Class

  • Header: QSqlDatabase

  • CMake:

    find_package(Qt6 REQUIRED COMPONENTS Sql)

    target_link_libraries(mytarget PRIVATE Qt6::Sql)

  • qmake: QT += sql

  • Group: QSqlDatabase is part of Database Classes

Detailed Description

The QSqlDatabase class provides an interface for accessing a database through a connection. An instance of QSqlDatabase represents the connection. The connection provides access to the database via one of the supported database drivers, which are derived from QSqlDriver. Alternatively, you can subclass your own database driver from QSqlDriver. See How to Write Your Own Database Driver for more information.

Create a connection (i.e., an instance of QSqlDatabase) by calling one of the static addDatabase() functions, where you specify the driver or type of driver to use (depending on the type of database) and a connection name. A connection is known by its own name, not by the name of the database it connects to. You can have multiple connections to one database. QSqlDatabase also supports the concept of a default connection, which is the unnamed connection. To create the default connection, don't pass the connection name argument when you call addDatabase(). Subsequently, the default connection will be assumed if you call any static member function without specifying the connection name. The following snippet shows how to create and open a default connection to a PostgreSQL database:

 
Sélectionnez
    QSqlDatabase db = QSqlDatabase::addDatabase("QPSQL");
    db.setHostName("acidalia");
    db.setDatabaseName("customdb");
    db.setUserName("mojito");
    db.setPassword("J0a1m8");
    bool ok = db.open();

Once the QSqlDatabase object has been created, set the connection parameters with setDatabaseName(), setUserName(), setPassword(), setHostName(), setPort(), and setConnectOptions(). Then call open() to activate the physical connection to the database. The connection is not usable until you open it.

The connection defined above will be the default connection, because we didn't give a connection name to addDatabase(). Subsequently, you can get the default connection by calling database() without the connection name argument:

 
Sélectionnez
    QSqlDatabase db = QSqlDatabase::database();

QSqlDatabase is a value class. Changes made to a database connection via one