|  | Home · Overviews · Examples

# QSqlDatabase Class Reference
[com.trolltech.qt.sql module]

The `QSqlDatabase` class represents a connection to a database. More...

## Detailed Description

The `QSqlDatabase` class represents a connection to a database.

The `QSqlDatabase` class provides an abstract interface for accessing database backends. It relies on database-specific `QSqlDriver`s to actually access and manipulate data.

The following code shows how to initialize a connection:

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

Once a `QSqlDatabase` object has been created you can set the connection parameters with `setDatabaseName`, `setUserName`, `setPassword`, `setHostName`, `setPort`, and `setConnectOptions`. Once the parameters have been set up you can call `open` to open the connection.

The connection defined above is a nameless connection. It is the default connection and can be accessed using `database` later on:

            QSqlDatabase db = QSqlDatabase::database();

To make programming more convenient, `QSqlDatabase` is a value class. Any changes done to a database connection through one `QSqlDatabase` object will affect other `QSqlDatabase` objects representing the same connection. Call `cloneDatabase` if you want to create an independent database connection based on an existing one.

If you need multiple database connections simultaneously, specify an arbitrary name to `addDatabase` and `database`. Call `removeDatabase` to remove connections. `QSqlDatabase` will output a warning if you try to remove a connection referenced by other `QSqlDatabase` objects. Use `contains` to see if a given connection name is in the list of connections.

Once a connection is established you can see what tables the database offers with `tables`, find the primary index for a table with `primaryIndex`, get meta-information about a table's fields (e.g., their names) with `record`, and execute a query with `exec`.

If transactions are supported, you can use `transaction` to start a transaction, and then `commit` or `rollback` to complete it. You can find out whether transactions are supported using QSqlDriver::hasFeature(). When using transactions you must start the transaction before you create your query.

If an error occurred, it is given by `lastError`.

The names of the underlying SQL drivers are available from `drivers`; you can check for a particular driver with `isDriverAvailable`. If you have created your own custom driver, you can register it with `registerSqlDriver`.

See also `QSqlDriver`, `QSqlQuery`, `QtSql Module`, and Threads and the SQL Module.