Home · All Classes · Main Classes · Grouped Classes · Modules · Functions

SQL Database Drivers

The QtSql module uses driver plugins to communicate with the different database APIs. Since Qt's SQL Module API is database-independent, all database-specific code is contained within these drivers. Several drivers are supplied with Qt and other drivers can be added. The driver source code is supplied and can be used as a model for writing your own drivers.

Supported Databases

The table below lists the drivers included with Qt. Due to license incompatibilities with the GPL, not all of the plugins are provided with the Qt Open Source Edition.

Driver nameDBMS
QDB2IBM DB2 (version 7.1 and above)
QIBASEBorland InterBase
QMYSQLMySQL
QOCIOracle Call Interface Driver
QODBCOpen Database Connectivity (ODBC) - Microsoft SQL Server and other ODBC-compliant databases
QPSQLPostgreSQL (versions 7.3 and above)
QSQLITE2SQLite version 2
QSQLITESQLite version 3
QTDSSybase Adaptive Server

Note: To build a driver plugin you need to have the appropriate client library for your Database Management System (DBMS). This provides access to the API exposed by the DBMS, and is typically shipped with it. Most installation programs also allow you to install "development libraries", and these are what you need. These libraries are responsible for the low-level communication with the DBMS.

Building the Drivers Using Configure

On Unix and Mac OS X, the Qt configure script tries to automatically detect the available client libraries on your machine. Run configure -help to see what drivers can be built. You should get an output similar to this:

    -no-sql-<driver> ... Disable SQL <driver> entirely.
    -qt-sql-<driver> ... Enable a SQL <driver> in the Qt Library, by default
                         none are turned on.
    -plugin-sql-<driver> Enable SQL <driver> as a plugin to be linked to
                         at run time.

                         Possible values for <driver>:
                         [ db2 ibase mysql oci odbc psql sqlite sqlite2 tds ]

The configure script cannot detect the neccessary libraries and include files if they are not in the standard paths, so it may be necessary to specify these paths using the -I and -L command-line options. For example, if your MySQL include files are installed in /usr/local/mysql (or in C:\mysql\include on Windows), then pass the following parameter to configure: -I/usr/local/mysql (or -I C:\mysql\include for Windows).

On Windows the -I parameter doesn't accept spaces in filenames, so use the 8.3 name instead; for example, use C:\progra~1\mysql instead of C:\Program Files\mysql.

Use the -qt-sql-<driver> parameter to build the database driver statically into your Qt library or -plugin-sql-<driver> to build the driver as a plugin. Look at the sections that follow for additional information about required libraries.

Building the Plugins Manually

QMYSQL for MySQL (Version 3.x and Above)

General Information

MySQL 3.x doesn't support SQL transactions by default, although there are some backends which offer this functionality. Recent versions of the MySQL client libraries (>3.23.34) allow you to use transactions on those modified servers.

If you have a recent client library and connect to a transaction-enabled MySQL server, a call to the QSqlDriver::hasFeature(QSqlDriver::Transactions) function returns true and SQL transactions can be used.

If the plugin is compiled against MySQL 4.x client libraries, transactions are enabled by default.

You can find information about MySQL on http://www.mysql.com

Stored Procedure Support

MySQL 5 introduces stored procedure support at the SQL level, but no API to control IN, OUT and INOUT parameters. Therefore, parameters have to be set and read using SQL commands instead of QSqlQuery::bindValue().

Example stored procedure:

    create procedure qtestproc (OUT param1 INT, OUT param2 INT)
    BEGIN
        set param1 = 42;
        set param2 = 43;
    END

Source code to access the OUT values:

        QSqlQuery q;
        q.exec("call qtestproc (@outval1, @outval2)");
        q.exec("select @outval1, @outval2");
        q.next();
        qDebug() << q.value(0) << q.value(1); // outputs "42" and "43"

Note: @outval1 and @outval2 are variables local to the current connection and will not be affected by queries sent from another host or connection.

Embedded MySQL Server

The MySQL embedded server is a drop-in replacement for the normal client library. With the embedded MySQL server, a MySQL server is not required to use MySQL functionality.

To use the embedded MySQL server, simply link the Qt plugin to libmysqld instead of libmysqlclient. This can be done by replacing -lmysqlclient_r by -lmysqld in the qmake command in the section below.

Please refer to the MySQL documentation, chapter "libmysqld, the Embedded MySQL Server Library" for more information about the MySQL embedded server.

How to Build the Plugin on Unix and Mac OS X

You need the MySQL header files and as well as the shared library libmysqlclient.so. Depending on your Linux distribution you may need to install a package which is usually called "mysql-devel".

Tell qmake where to find the MySQL header files and shared libraries (here it is assumed that MySQL is installed in /usr/local) and run make:

        cd $QTDIR/src/plugins/sqldrivers/mysql
        qmake -o Makefile "INCLUDEPATH+=/usr/local/include" "LIBS+=-L/usr/local/lib -lmysqlclient_r" mysql.pro
        make

How to Build the Plugin on Windows

You need to get the MySQL installation files. Run SETUP.EXE and choose "Custom Install". Install the "Libs & Include Files" Module. Build the plugin as follows (here it is assumed that MySQL is installed in C:\MySQL):

        cd %QTDIR%\src\plugins\sqldrivers\mysql
        qmake -o Makefile "INCLUDEPATH+=C:\MySQL\include" "LIBS+=C:\MySQL\lib\opt\libmysql.lib" mysql.pro
        nmake

If you are not using a Microsoft compiler, replace nmake with make in the line above.

QOCI for the Oracle Call Interface (OCI)

General Information

The Qt OCI plugin supports Oracle 9i, 10g and higher. After connecting to the Oracle server, the plugin will auto-detect the database version and enable features accordingly.

User Authentication

The Qt OCI plugin supports authentication using external credentials (OCI_CRED_EXT). Usually, this means that the database server will use the user authentication provided by the operating system instead of its own authentication mechanism.

Leave the username and password empty when opening a connection with QSqlDatabase to use the external credentials authentication.

BLOB/LOB Support

Binary Large Objects (BLOBs) can be read and written, but be aware that this process may require a lot of memory. You should use a forward only query to select LOB fields (see QSqlQuery::setForwardOnly()).

Inserting BLOBs should be done using either a prepared query where the BLOBs are bound to placeholders or QSqlTableModel, which uses a prepared query to do this internally.

How to Build the Plugin on Unix and Mac OS X

For Oracle 10g, all you need is the "Instant Client Package - Basic" and "Instant Client Package - SDK". For Oracle prior to 10g, you require the standard Oracle client and the SDK packages.

Oracle library files required to build the driver:

Tell qmake where to find the Oracle header files and shared libraries and run make:

For Oracle version 9:

        cd $QTDIR/src/plugins/sqldrivers/oci
        qmake -o Makefile "INCLUDEPATH+=$ORACLE_HOME/rdbms/public $ORACLE_HOME/rdbms/demo" "LIBS+=-L$ORACLE_HOME/lib -lclntsh -lwtc9" oci.pro
        make

For Oracle version 10, we assume that you installed the RPM packages of the Instant Client Package SDK (you need to adjust the version number accordingly):

        cd $QTDIR/plugins/src/sqldrivers/oci
        qmake -o Makefile "INCLUDEPATH+=/usr/include/oracle/10.1.0.3/client/" "LIBS+=-L/usr/lib/oracle/10.1.0.3/client/lib" oci.pro
        make

How to Build the Plugin on Windows

Choosing the option "Programmer" in the Oracle Client Installer from the Oracle Client Installation CD is sufficient to build the plugin.

Build the plugin as follows (here it is assumed that Oracle Client is installed in C:\oracle):

        set INCLUDE=%INCLUDE%;c:\oracle\oci\include
        set LIB=%LIB%;c:\oracle\oci\lib\msvc
        cd %QTDIR%\src\plugins\sqldrivers\oci
        qmake -o Makefile oci.pro
        nmake

If you are not using a Microsoft compiler, replace nmake with make in the line above.

When you run your application you will also need to add the oci.dll path to your PATH environment variable:

        set PATH=%PATH%;c:\oracle\bin

QODBC for Open Database Connectivity (ODBC)

General Information

ODBC is a general interface that allows you to connect to multiple DBMSs using a common interface. The QODBC driver allows you to connect to an ODBC driver manager and access the available data sources. Note that you also need to install and configure ODBC drivers for the ODBC driver manager that is installed on your system. The QODBC plugin then allows you to use these data sources in your Qt applications.

Note: You should use native drivers in preference to the ODBC driver where they are available. ODBC support can be used as a fallback for compliant databases if no native drivers are available.

On Windows an ODBC driver manager should be installed by default. For Unix systems there are some implementations which must be installed first. Note that every client that uses your application is required to have an ODBC driver manager installed, otherwise the QODBC plugin will not work.

Be aware that when connecting to an ODBC datasource you must pass in the name of the ODBC datasource to the QSqlDatabase::setDatabaseName() function rather than the actual database name.

The QODBC Plugin needs an ODBC compliant driver manager version 2.0 or later to work. Some ODBC drivers claim to be version 2.0 compliant, but do not offer all the necessary functionality. The QODBC plugin therefore checks whether the data source can be used after a connection has been established and refuses to work if the check fails. If you don't like this behavior, you can remove the #define ODBC_CHECK_DRIVER line from the file qsql_odbc.cpp. Do this at your own risk!

If you experience very slow access of the ODBC datasource, make sure that ODBC call tracing is turned off in the ODBC datasource manager.

Unicode Support

The QODBC Plugin will use the Unicode API if UNICODE is defined. On Windows NT based systems, this is the default. Note that the ODBC driver and the DBMS must also support Unicode.

For the Oracle 9 ODBC driver (Windows), it is neccessary to check "SQL_WCHAR support" in the ODBC driver manager otherwise Oracle will convert all Unicode strings to local 8-bit.

How to Build the Plugin on Unix and Mac OS X

It is recommended that you use unixODBC. You can find the latest version and ODBC drivers at http://www.unixodbc.org. You need the unixODBC header files and shared libraries.

Tell qmake where to find the unixODBC header files and shared libraries (here it is assumed that unixODBC is installed in /usr/local/unixODBC) and run make:

        cd $QTDIR/src/plugins/sqldrivers/odbc
        qmake "INCLUDEPATH+=/usr/local/unixODBC/include" "LIBS+=-L/usr/local/unixODBC/lib -lodbc"
        make

How to Build the Plugin on Windows

The ODBC header and include files should already be installed in the right directories. You just have to build the plugin as follows:

        cd %QTDIR%\src\plugins\sqldrivers\odbc
        qmake -o Makefile odbc.pro
        nmake

If you are not using a Microsoft compiler, replace nmake with make in the line above.

QPSQL for PostgreSQL (Version 7.3 and Above)

General Information

The QPSQL driver supports version 7.3 and higher of PostgreSQL.

For more information about PostgreSQL visit http://www.postgresql.org.

Unicode Support

The QPSQL driver automatically detects whether the PostgreSQL database you are connecting to supports Unicode or not. Unicode is automatically used if the server supports it. Note that the driver only supports the UTF-8 encoding. If your database uses any other encoding, the server must be compiled with Unicode conversion support.

Unicode support was introduced in PostgreSQL version 7.1 and it will only work if both the server and the client library have been compiled with multibyte support. More information about how to set up a multibyte enabled PostgreSQL server can be found in the PostgreSQL Administrator Guide, Chapter 5.

BLOB Support

Binary Large Objects are supported through the BYTEA field type in PostgreSQL server versions >= 7.1.

How to Build the Plugin on Unix and Mac OS X

You need the PostgreSQL client library and headers installed.

To make qmake find the PostgreSQL header files and shared libraries, run qmake the following way (assuming that the PostgreSQL client is installed in /usr):

        cd $QTDIR/src/plugins/sqldrivers/psql
        qmake -o Makefile "INCLUDEPATH+=/usr/include/pgsql" "LIBS+=-L/usr/lib -lpq" psql.pro
        make

How to Build the Plugin on Windows

Install the PostgreSQL developer libraries. Assuming that PostgreSQL was installed in C:\psql, build the plugin as follows:

        cd %QTDIR%\src\plugins\sqldrivers\psql
        qmake -o Makefile "INCLUDEPATH+=C:\psql\include" "LIBS+=C:\psql\lib\ms\libpq.lib" psql.pro
        nmake

QTDS for Sybase Adaptive Server

How to Build the Plugin on Unix and Mac OS X

Under Unix, two libraries are available which support the TDS protocol:

Regardless of which library you use, the shared object file libsybdb.so is needed. Set the SYBASE environment variable to point to the directory where you installed the client library and execute qmake:

        cd $QTDIR/src/plugins/sqldrivers/tds
        qmake -o Makefile "INCLUDEPATH=$SYBASE/include" "LIBS=-L$SYBASE/lib -lsybdb"
        make

How to Build the Plugin on Windows

You can either use the DB-Library supplied by Microsoft or the Sybase Open Client (http://www.sybase.com). You must include NTWDBLIB.LIB to build the plugin:

        cd %QTDIR%\src\plugins\sqldrivers\tds
        qmake -o Makefile "LIBS+=NTWDBLIB.LIB" tds.pro
        nmake

By default the Microsoft library is used on Windows, if you want to force the use of the Sybase Open Client, you must define Q_USE_SYBASE in %QTDIR%\src\sql\drivers\tds\qsql_tds.cpp. If you are not using a Microsoft compiler, replace nmake with make in the line above.

QDB2 for IBM DB2 (Version 7.1 and Above)

General Information

The Qt DB2 plugin makes it possible to access IBM DB2 databases. It has been tested with IBM DB2 v7.1 and 7.2. You must install the IBM DB2 development client library, which contains the header and library files necessary for compiling the QDB2 plugin.

The QDB2 driver supports prepared queries, reading/writing of Unicode strings and reading/writing of BLOBs.

We suggest using a forward-only query when calling stored procedures in DB2 (see QSqlQuery::setForwardOnly()).

How to Build the Plugin on Unix and Mac OS X

        cd $QTDIR/src/plugins/sqldrivers/db2
        qmake -o Makefile "INCLUDEPATH+=$DB2DIR/include" "LIBS+=-L$DB2DIR/lib -ldb2"
        make

How to Build the Plugin on Windows

The DB2 header and include files should already be installed in the right directories. You just have to build the plugin as follows:

        cd %QTDIR%\src\plugins\sqldrivers\db2
        qmake -o Makefile "INCLUDEPATH+=<DB2 home>/sqllib/include" "LIBS+=<DB2 home>/sqllib/lib/db2cli.lib"
        nmake

If you are not using a Microsoft compiler, replace nmake with make in the line above.

QSQLITE2 for SQLite Version 2

The Qt SQLite 2 plugin is offered for compatibility. Whenever possible, use the version 3 plugin instead. The build instructions for version 3 apply to version 2 as well.

QSQLITE for SQLite (Version 3 and Above)

General Information

The Qt SQLite plugin makes it possible to access SQLite databases. SQLite is an in-process database, which means that it is not necessary to have a database server. SQLite operates on a single file, which must be set as the database name when opening a connection. If the file does not exist, SQLite will try to create it. SQLite also supports in-memory databases, simply pass ":memory:" as the database name.

SQLite has some restrictions regarding multiple users and multiple transactions. If you try to read/write on a resource from different transactions, your application might freeze until one transaction commits or rolls back. The Qt SQLite driver will retry to write to a locked resource until it runs into a timeout (see QSQLITE_BUSY_TIMEOUT at QSqlDatabase::setConnectOptions()).

SQLite has no support for types, every value is treated as character data.

You can find information about SQLite on http://www.sqlite.org.

How to Build the Plugin

SQLite version 3 is included as a third-party library within Qt. It can be built by passing the following parameters to the configure script: -plugin-sql-sqlite (build as a plugin) or -qt-sql-sqlite (linked directly into the Qt library).

If you don't want to use the SQLite library included with Qt, you can build it manually (replace $SQLITE by the directory where SQLite resides):

        cd $QTDIR/src/plugins/sqldrivers/sqlite
        qmake -o Makefile "INCLUDEPATH+=$SQLITE/include" "LIBS+=-L$SQLITE/lib -lsqlite"
        make

On Windows:

        cd %QTDIR%\src\plugins\sqldrivers\sqlite
        qmake -o Makefile "INCLUDEPATH+=C:\SQLITE\INCLUDE" "LIBS+=C:\SQLITE\LIB\SQLITE3.LIB" mysql.pro
        nmake

File Format Compatibility

SQLite minor releases sometimes break file format forward compatibility. For example, SQLite 3.3 can read database files created with SQLite 3.2, but databases created with SQLite 3.3 cannot be read by SQLite 3.2. Please refer to the SQLite documentation and change logs for information about file format compatibility between versions.

Qt minor releases usually follow the SQLite minor releases, while Qt patch releases follow SQLite patch releases. Patch releases are therefore both backward and forward compatible.

To force SQLite to use a specific file format, it is neccessary to build and ship your own database plugin with your own SQLite library as illustrated above. Some versions of SQLite can be forced to write a specific file format by setting the SQLITE_DEFAULT_FILE_FORMAT define when building SQLite.

QIBASE for Borland InterBase

General Information

The Qt InterBase plugin makes it possible to access the InterBase and Firebird databases. InterBase can either be used as a client/server or without a server in which case it operates on local files. The database file must exist before a connection can be established.

Note that InterBase requires you to specify the full path to the database file, no matter whether it is stored locally or on another server.

        db.setHostName("MyServer");
        db.setDatabaseName("C:\\test.gdb");

You need the InterBase/Firebird development headers and libraries to build this plugin.

Due to license incompatibilities with the GPL, users of the Qt Open Source Edition are not allowed to link this plugin to the commercial editions of InterBase. Please use Firebird or the free edition of InterBase.

How to Build the Plugin on Unix and Mac OS X

The following assumes InterBase or Firebird is installed in /opt/interbase:

        cd $QTDIR/src/plugins/sqldrivers/ibase
        qmake -o Makefile "INCLUDEPATH+=/opt/interbase/include" "LIBS+=-L/opt/interbase/lib" ibase.pro
        make

How to Build the Plugin on Windows

The following assumes InterBase or Firebird is installed in C:\interbase:

        cd %QTDIR%\src\plugins\sqldrivers\ibase
        qmake -o Makefile "INCLUDEPATH+=C:\interbase\include" ibase.pro
        nmake

If you are not using a Microsoft compiler, replace nmake with make in the line above.

Note that C:\interbase\bin must be in the PATH.

Troubleshooting

You should always use client libraries that have been compiled with the same compiler as you are using for your project. If you cannot get a source distibution to compile the client libraries yourself, you must make sure that the pre-compiled library is compatible with your compiler, otherwise you will get a lot of "undefined symbols" errors. Some compilers have tools to convert libraries, e.g. Borland ships the tool COFF2OMF.EXE to convert libraries that have been generated with Microsoft Visual C++.

If the compilation of a plugin succeeds but it cannot be loaded, make sure that the following requirements are met:

If you are experiencing problems with loading plugins, and see output like this

        QSqlDatabase: QMYSQL driver not loaded
        QSqlDatabase: available drivers: QMYSQL

the problem is probably that the plugin had the wrong build key. For debugging purposes, remove the corresponding entry in the $HOME/.qt/qt_plugins_(qtversion).rc file.

The next time you try to load this plugin, it will give you a more detailed error message.

How to Write Your Own Database Driver

QSqlDatabase is responsible for loading and managing database driver plugins. When a database is added (see QSqlDatabase::addDatabase()), the appropriate driver plugin is loaded (using QSqlDriverPlugin). QSqlDatabase relies on the driver plugin to provide interfaces for QSqlDriver and QSqlResult.

QSqlDriver is an abstract base class which defines the functionality of a SQL database driver. This includes functions such as QSqlDriver::open() and QSqlDriver::close(). QSqlDriver is responsible for connecting to a database, establish the proper environment, etc. In addition, QSqlDriver can create QSqlQuery objects appropriate for the particular database API. QSqlDatabase forwards many of its function calls directly to QSqlDriver which provides the concrete implementation.

QSqlResult is an abstract base class which defines the functionality of a SQL database query. This includes statements such as SELECT, UPDATE, and ALTER TABLE. QSqlResult contains functions such as QSqlResult::next() and QSqlResult::value(). QSqlResult is responsible for sending queries to the database, returning result data, etc. QSqlQuery forwards many of its function calls directly to QSqlResult which provides the concrete implementation.

QSqlDriver and QSqlResult are closely connected. When implementing a Qt SQL driver, both of these classes must to be subclassed and the abstract virtual methods in each class must be implemented.

To implement a Qt SQL driver as a plugin (so that it is recognized and loaded by the Qt library at runtime), the driver must use the Q_EXPORT_PLUGIN2() macro. Read How to Create Qt Plugins for more information on this. You can also check out how this is done in the SQL plugins that are provided with Qt in QTDIR/src/plugins/sqldrivers and QTDIR/src/sql/drivers.

The following code can be used as a skeleton for a SQL driver:

    class XyzResult : public QSqlResult
    {
    public:
        XyzResult(const QSqlDriver *driver)
            : QSqlResult(driver) {}
        ~XyzResult() {}

    protected:
        QVariant data(int /* index */) { return QVariant(); }
        bool isNull(int /* index */) { return false; }
        bool reset(const QString & /* query */) { return false; }
        bool fetch(int /* index */) { return false; }
        bool fetchFirst() { return false; }
        bool fetchLast() { return false; }
        int size() { return 0; }
        int numRowsAffected() { return 0; }
        QSqlRecord record() { return QSqlRecord(); }
    };

    class XyzDriver : public QSqlDriver
    {
    public:
        XyzDriver() {}
        ~XyzDriver() {}

        bool hasFeature(DriverFeature /* feature */) const { return false; }
        bool open(const QString & /* db */, const QString & /* user */,
                  const QString & /* password */, const QString & /* host */,
                  int /* port */, const QString & /* options */)
            { return false; }
        void close() {}
        QSqlResult *createResult() const { return new XyzResult(this); }
    };


Copyright © 2006 Trolltech Trademarks
Qt 4.1.3