CopperSpice API  1.7.4
Connecting to Databases

To access a database with QSqlQuery or QSqlQueryModel, create and open one or more database connections. Database connections are normally identified by connection name, not by database name. You can have multiple connections to the same database. QSqlDatabase also supports the concept of a default connection, which is an unnamed connection. When calling QSqlQuery or QSqlQueryModel member functions that take a connection name argument, if you don not pass a connection name, the default connection will be used. Creating a default connection is convenient when your application only requires one database connection.

Note the difference between creating a connection and opening it. Creating a connection involves creating an instance of class QSqlDatabase. The connection is not usable until it is opened. The following code shows how to create a default connection and then open it.

bool ok =;

The first line creates the connection object, and the last line opens it for use. In between we initialize some connection information, including the database name, host name, user name, and password.

In this example we are connecting to the MySQL database flightdb on the host bigblue. The "QMYSQL" argument to QSqlDatabase::addDatabase() specifies the type of database driver to use for the connection. The set of database drivers included with CopperSpice are shown in the table on SQL Drivers

The connection in the following code will be the default connection, because we do not pass the second argument to QSqlDatabase::addDatabase(), which is the connection name. In this example, we establish two MySQL database connections named "first" and "second".

QSqlDatabase firstDB = QSqlDatabase::addDatabase("QMYSQL", "first");
QSqlDatabase secondDB = QSqlDatabase::addDatabase("QMYSQL", "second");

After these connections have been initialized, call QSqlDatabase::open() for each one to establish the live connections. If the QSqlDatabase::open() fails, it returns false. In that case, call QSqlDatabase::lastError() to get error information.

Once a connection is established, we can call the static function QSqlDatabase::database() from anywhere with a connection name to get a pointer to that database connection. If we do not pass a connection name, it will return the default connection.

To remove a database connection, first close the database using QSqlDatabase::close(), then remove it using the static method QSqlDatabase::removeDatabase().