Qt:Документация 4.3.2/sql-driver

Материал из Wiki.crossplatform.ru

Перейти к: навигация, поиск
40px Внимание: Актуальная версия перевода документации находится здесь

__NOTOC__

Image:qt-logo.png

Главная · Все классы · Основные классы · Классы по группам · Модули · Функции

Image:trolltech-logo.png

Содержание

[править] Драйвера баз данных SQL

Модуль QtSql использует плагины драйверов для взаимодействия с API различных баз данных. Так как API SQL модуля независит от баз данных, код специфичный для определенной БД содержится в этих драйверах. Некоторые драйвера поставляются с Qt, а другие могут быть добавлены. Исходный код драйверов также предоставляется и может быть использован как модель для написания собственных драйверов.


[править] Поддерживаемые базы данных

В таблице ниже представлен список драйверов поставляемых с Qt. Из-за несовместимости с GPL лицензией, не все плагины поставляются с Qt Open Source Edition.


Имя драйвера СУБД
QDB2 IBM DB2 (версия 7.1 и выше)
QIBASE Borland InterBase
QMYSQL MySQL
QOCI Oracle Call Interface Driver
QODBC Open Database Connectivity (ODBC) - Microsoft SQL Server и другие ODBC совместимые базы данных
QPSQL PostgreSQL (версия 7.3 и выше)
QSQLITE2 SQLite версия 2
QSQLITE SQLite версия 3
QTDS Sybase Adaptive Server

Замечаение: Для сборки плагина драйвера вам нужно иметь соответствующую клиентскую библиотеку для вашей системы управления базами данных (СУБД). Это обеспечивает доступ к API СУБД, и, как правило, поставляется вместе с ней. Большинство программ установки также позволяют установить "библиотеки для разработки", и то, что вам нужно. Эти библиотеки отвечают за низкоуровневое взаимодействия с СУБД.

[править] Сборка драйверов при запуске configure

Под Unix и Mac OS X, скрипт Qt configure пытается автоматически обнаружить доступные библиотеки на вашей машине. Запустив configure -help можно увидеть какие драйвера могут быть собраны. Вы получите подобный список:

 -no-sql-<driver> ... Выключить SQL <driver> полностью.
 -qt-sql-<driver> ... Включить SQL <driver> в Qt библиотеку, по умолчанию 
                      не включенную.
 -plugin-sql-<driver> Включить SQL <driver> как плагин для использования в run time.
 
                      Доступные значения для <driver>:
                      [ db2 ibase mysql oci odbc psql sqlite sqlite2 tds ]

Скрипт configure не может обнаружить необходимые библиотеки(*.lib) и include-файлы, если она находятся не в стандартных директориях, тогда вам может понадобиться указать путь к ним используя -I и -L опции командной строки. Например, если MySQL include-файлы установлены в /usr/local/mysql (или в C:\mysql\include под Windows), тогда добавьте следующий configure параметр: -I/usr/local/mysql (или -I C:\mysql\include для Windows).

Под Windows параметр -I не поддерживает пробелы в пути, тогда используйте 8.3 имена; например, используйте C:\progra~1\mysql вместо C:\Program Files\mysql.

Используйте параметр -qt-sql-<driver> для статической сборки БД драйвера с Qt библиотекой или -plugin-sql-<driver> для сборки драйвера как плагина. Для дополнительной информации о необходимых библиотеках, смотрите разделы далее.

[править] Сборка плагинов вручную

[править] QMYSQL для MySQL 4 и выше

[править] Поддержка хранимых процедур в QMYSQL

В MySQL 5 введена поддержка хранимых процедур SQL уровня, но нет API контроля IN, OUT и INOUT параметров. Поэтому, параметры должны быть установлены и прочитаны с использованием SQL команд вместо QSqlQuery::bindValue().

Пример хранимой процедуры:

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

Исходный код получения доступа к OUT значениям:

     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"

Замечание: @outval1 и @outval2 локальные переменные текущего соединения, они не будут участвовать в запросах отправленных с другого компьютера или соединения.

[править] Встраивание MySQL сервера

Встроенный MySQL сервер встраиваетс в нормальную клиентскую библиотеку. Чтобы использовать функциональность MySQL со встроенным MySQL-сервером, сервер MySQL не нужен.

Чтобы использовать встроенный сервер MySQL, просто слинкуйте Qt плагин с libmysqld вместо libmysqlclient. Это может быть сделано путем замены -lmysqlclient_r на -lmysqld в команде qmake в разделе ниже.

Пожалуйста, обратитесь к документации MySQL, глава "libmysqld, the Embedded MySQL Server Library", чтобы получить дополнительную информацию о встроенном сервере MySQL.

[править] Как собрать QMYSQL плагин под Unix и Mac OS X

Вам понадобятся заголовочные файлы MySQL с соответствующей им динамической библиотекой libmysqlclient.so. В зависимости от вашего дистрибутива вам может потребоваться установка пакета, который обычно называется "mysql-devel".

Укажите qmake, где искать MySQL header-файлы и библиотеки (например, MySQL установлен в /usr/local) и запустите make:

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

После установки Qt, как описано в документе Установка Qt/X11, вам нужно установить плагин в каталог по умолчанию:

     cd $QTDIR/src/plugins/sqldrivers/mysql
     make install
[править] Как собрать QMYSQL плагин под Windows

Вам нужно получить MySQL файлы инсталяции. Запустите SETUP.EXE и выбирите "Custom Install". Установите модуль "Libs & Include Files". Собирается плагин так: (например, MySQL установлен в 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

Если вы не используете компилятор от Microsoft, замените nmake на make.

[править] QOCI для Oracle Call Interface (OCI)

[править] Общая информация о OCI плагине

Плагин Qt OCI поддерживает Oracle 9i, 10g и выше. После соединения с сервером Oracle, плагин автоматически детектирует версию базы данных и вдопускает соответствующие особенности.

[править] OCI авторизация пользователя

Плагин Qt OCI поддерживает аутентификацию используя внешние учетные записи (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.

[править] Поддержка OCI BLOB/LOB

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.

[править] Как собрать OCI плагин под Unix и 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:

  • libclntsh.so (all versions)
  • libwtc9.so (only Oracle 9)

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
[править] Как собрать OCI плагин под 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 для Open Database Connectivity (ODBC)

[править] Общая информация о ODBC плагине

ODBC это общий интерфейс, который позволяет вам соеденятся с множеством СУБД используя общий интерфейс. Драйвер QODBC позволяет вам соеденятся с "Источником данных ODBC" и получать доступ к имеющимся источникам данных. Заметьте, что вы так же нуждаетесь в установке и настройке драйверов ODBC для "Источника данных ODBC", который установлен на вашей системе. Плагин QODBC позволит вам использовать эти источники данных в ваших Qt приложениях.

Замечание: Вы должны использовать родные драйверы предпочитая их драйверу ODBC, там где это возможно. Поддержка ODBC может быть использована, как обходной путь для баз данных если родной драйвер не доступен.

На Windows "Источник данных ODBC" должен быть установлен по умолчанию. Для Unix систем есть нескользо реализаций, которые должны быть сначало установлены. Заметьте, что каждый клиент, который использует ваше приложение, требует наличия установленного "Источника данных ODBC", в противном случае плагин QODBC не будет работать.

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.

[править] Поддержка ODBC хранимых процедур

With Microsoft SQL Server the result set returned by a stored procedure that uses the return statement, or returns multiple result sets, will be accessible only if you set the query's forward only mode to forward using QSqlQuery::setForwardOnly().

 \\ STORED_PROC uses the return statement or returns multiple result sets
 QSqlQuery query;
 query.setForwardOnly(true);
 query.exec("{call STORED_PROC}");

Note: The value returned by the stored procedure's return statement is discarded. If the stored procedure returns multiple result sets only the first will be accessible.

[править] Поддержка ODBC Unicode

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.

[править] Как собрать ODBC плагин под Unix и 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
[править] Как собрать ODBC плагин под 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 для PostgreSQL (Версия 7.3 и выше)

[править] Общая информация о QPSQL драйвере

The QPSQL driver supports version 7.3 and higher of PostgreSQL.

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

[править] Поддержка QPSQL Unicode

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.

[править] Поддержка QPSQL BLOB

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

[править] Как собрать QPSQL плагин под Unix и 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

After installing Qt, as described in the Installing Qt/X11 document, you also need to install the plugin in the standard location:

     cd $QTDIR/src/plugins/sqldrivers/psql
     make install
[править] Как собрать QPSQL плагин под 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 для Sybase Adaptive Server

[править] Общая информация о QTDS

It is not possible to set the port with QSqlDatabase::setPort() due to limitations in the Sybase client library. Refer to the Sybase documentation for information on how to set up a Sybase client configuration file to enable connections to databases on non-default ports.

[править] Как собрать QDTS плагин под Unix и 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
[править] Как собрать QDTS плагин под 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 для IBM DB2 (Версия 7.1 и выше)

[править] Общая информация о QDB2

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()).

[править] Как собрать QDB2 плагин под Unix и Mac OS X
     cd $QTDIR/src/plugins/sqldrivers/db2
     qmake -o Makefile "INCLUDEPATH+=$DB2DIR/include" "LIBS+=-L$DB2DIR/lib -ldb2"
     make

After installing Qt, as described in the Installing Qt/X11 document, you also need to install the plugin in the standard location:

     cd $QTDIR/src/plugins/sqldrivers/db2
     make install
[править] Как собрать QDB2 плагин под 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 для SQLite Версия 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 для SQLite (версия 3 и выше)

[править] Общая информация о QSQLITE

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 doesn't have a type-system like other databases, so Qt will interpret fields as strings.

The driver is locked for updates while a select is executed. This may cause problems when using QSqlTableModel because Qt's item views fetch data as needed (with QSqlQuery::fetchMore() in the case of QSqlTableModel).

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

[править] Как собрать QSQLITE плагин

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

After installing Qt, as described in the Installing Qt/X11 document, you also need to install the plugin in the standard location:

     cd $QTDIR/src/plugins/sqldrivers/sqlite
     make install

On Windows:

     cd %QTDIR%\src\plugins\sqldrivers\sqlite
     qmake -o Makefile "INCLUDEPATH+=C:\SQLITE\INCLUDE" "LIBS+=C:\SQLITE\LIB\SQLITE3.LIB" sqlite.pro
     nmake
[править] Совместимость файловых форматов QSQLITE

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 для Borland InterBase

[править] Общая информация о QIBASE

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.

[править] Поддержка QIBASE Unicode и кодировка текста

By default the driver connects to the database using UNICODE_FSS. This can be overridden by setting the ISC_DPB_LC_CTYPE parameter with QSqlDatabase::setConnectOptions() before opening the connection.

    // connect to database using the Latin-1 character set
    db.setConnectOptions("ISC_DPB_LC_CTYPE=Latin1");
    db.open();

If Qt doesn't support the given text encoding the driver will issue a warning message and connect to the database using UNICODE_FSS.

Note that if the text encoding set when connecting to the database is not the same as in the database, problems with transliteration might arise.

[править] Хранимые процедуры QIBASE

InterBase/Firebird return OUT values as result set, so when calling stored procedure, only IN values need to be bound via QSqlQuery::bindValue(). The RETURN/OUT values can be retrieved via QSqlQuery::value(). Example:

 QSqlQuery q;
 q.exec("execute procedure my_procedure");
 q.next();
 qDebug() << q.value(0); // outputs the first RETURN/OUT value
[править] Как собрать QIBASE плагин под Unix и Mac OS X

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

If you are using InterBase:

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

If you are using Firebird, the Firebird library has to be set explicitely:

     cd $QTDIR/src/plugins/sqldrivers/ibase
     qmake -o Makefile "INCLUDEPATH+=/opt/interbase/include" "LIBS+=-L/opt/interbase/lib -lfbclient" ibase.pro
     make
[править] Как собрать QIBASE плагин под Windows

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

If you are using InterBase:

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

If you are using Firebird, the Firebird library has to be set explicitely:

     cd %QTDIR%\src\plugins\sqldrivers\ibase
     qmake -o Makefile "INCLUDEPATH+=C:\interbase\include" "LIBS+=-lfbclient" 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.

[править] Решение проблем

Вы должны всегда использовать библиотеки клиента, которые были собраны тем же компилятором, который вы используете для своего проекта. Если вы не можете получить описание источника сборки библиотеки клиента самостоятельно, попробуйте удостовериться, что предсобранная библиотека совместима с вашим компилятором, иначе вы получите множество ошибок. Некоторые компиляторы имеют инструменты для преобразования библиотек, например: Borland предоставляет инструмент COFF2OMF.EXE, для преобразования библиотек, которые были собраны в Microsoft Visual C++.

Если компиляция плагина прошла успешно, но он не может быть загружен, убедитесь в том, что следующие требования выполнены:

  • Убедитесь, что вы используете shared Qt библиотеку; вы не может использовать плагины в статической сборке.
  • Убедитесь, что плагин в правильной директории. Для этого можно использовать QApplication::libraryPaths(), чтобы определить, где Qt ищет плагины.
  • Убедитесь, что клиентские библиотеки СУБД доступны. Под Unix, выполните команду ldd и введите имя плагина в качестве параметра, например: ldd libqsqlmysql.so. Вы получите предупреждение, если какая-то из клиентских библиотек не найдена. Под Windows, вы можете использовать Visual Studio dependency walker.
  • Скомпилируйте Qt с установленным QT_DEBUG_COMPONENT, чтобы получить более подробную отладочную информацию, когда загружаются плагины.

Если у вас возникли проблемы с загрузкой плагинов, и вы видите ошибку вроде этой:

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

проблема вероятно в том, что плагин имеет неправильный ключ сборки. Для отладки удалите соответствующую запись в $HOME/.qt/qt_plugins_(qtversion).rc файле.

После чего снова попытайтесь загрузить этот плагин, и вы получите более детальное описание ошибки.

[править] Как написать собственный драйвер БД

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 &amp; /* 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 &amp; /* db */, const QString &amp; /* user */,
               const QString &amp; /* password */, const QString &amp; /* host */,
               int /* port */, const QString &amp; /* options */)
         { return false; }
     void close() {}
     QSqlResult *createResult() const { return new XyzResult(this); }
 };

Copyright © 2007 Trolltech Trademarks
Qt 4.3.2