Драйверы баз данных SQL
|
Имя драйверов | DBMS |
---|---|
QDB2 | IBM DB2 (версия 7.1 и выше) |
QIBASE | Borland InterBase |
QMYSQL | MySQL |
QOCI | Драйвер Oracle Call Interface |
QODBC | Open Database Connectivity (ODBC) - Microsoft SQL Server и другие ODBC-совместимые базы данных |
QPSQL | PostgreSQL (версия 7.3 и выше) |
QSQLITE2 | SQLite версии 2 |
QSQLITE | SQLite версии 3 |
QTDS | Драйвер Sybase Adaptive Server |
Замечание: для сборки плагина драйвера вам нужно иметь соответствующую клиентскую библиотеку для вашей системы управления базами данных (СУБД). Это обеспечивает доступ к API СУБД, и, как правило, поставляется вместе с ней. Большинство программ установки также позволяют установить "библиотеки для разработки", это то, что вам нужно. Эти библиотеки отвечают за низкоуровневое взаимодействие с СУБД.
Под Unix и Mac OS X, скрипт Qt configure пытается автоматически обнаружить доступные библиотеки на вашей машине. Запустив configure -help можно увидеть, какие драйвера могут быть собраны. Вы получите подобный список, подобный следующему:
-no-sql-<driver> ... Выключить SQL <driver> полностью. -qt-sql-<driver> ... Включить SQL <driver> в Qt библиотеку, по умолчанию не включенную. -plugin-sql-<driver> Включить SQL <driver> как плагин для подключения во время выполнения программы. Доступные значения для <driver>: [ db2 ibase mysql oci odbc psql sqlite sqlite2 tds ]
Скрипт configure не может обнаружить необходимые библиотеки и подключаемые (include) файлы, если они находятся не в стандартных директориях, вам может понадобиться указать путь к ним, используя опции командной строки -I и -L. Например, если MySQL включаемые файлы установлены в /usr/local/mysql (или в C:\mysql\include под Windows), тогда добавьте следующий параметр: -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> для сборки драйвера в виде плагина. Для дополнительной информации о необходимых библиотеках смотрите разделы ниже.
В MySQL 5 введена поддержка хранимых процедур SQL уровня, но нет API контроля для IN, OUT и INOUT параметров. Поэтому, параметры должны быть установлены и прочитаны с использованием 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); // выводит "42" и "43"
Замечание: @outval1 и @outval2 - локальные переменные текущего соединения, они не будут участвовать в запросах, отправленных с другого компьютера или соединения.
Встроенный MySQL сервер является лёгкой заменой обычной клиентской библиотеке. Чтобы использовать функциональность MySQL со встроенным MySQL-сервером, сервер MySQL не нужен.
Чтобы использовать встроенный сервер MySQL, просто слинкуйте Qt плагин с libmysqld вместо libmysqlclient. Это может быть сделано путем замены -lmysqlclient_r на -lmysqld в команде qmake в разделе ниже.
Пожалуйста, обратитесь к документации MySQL, глава "libmysqld, the Embedded MySQL Server Library", чтобы получить дополнительную информацию о встроенном сервере MySQL.
Вам понадобятся заголовочные файлы MySQL с соответствующей им динамической библиотекой libmysqlclient.so. В зависимости от вашего дистрибутива вам может потребоваться установка пакета, который обычно называется "mysql-devel".
Укажите qmake , где искать MySQL header-файлы и библиотеки (например, MySQL установлен в /usr/local) и запустите make:
cd $QTDIR/src/plugins/sqldrivers/mysql qmake "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
Вам нужно получить файлы инсталяции MySQL. Запустите SETUP.EXE и выбирите "Custom Install". Установите модуль "Libs & Include Files". Соберите плагин подобно тому, как показано ниже: (в примере MySQL установлен в C:\MySQL):
cd %QTDIR%\src\plugins\sqldrivers\mysql qmake "INCLUDEPATH+=C:\MySQL\include" "LIBS+=C:\MYSQL\MySQL Server <version>\lib\opt\libmysql.lib" mysql.pro nmake
Если вы используете компилятор не от Microsoft, замените nmake на make.
Замечание: Этот плагин базы данных не поддерживается для Windows CE.
[FIXME] Note: Including "-o Makefile" as an argument to qmake to tell it where to build the makefile can cause the plugin to be built in release mode only. Если вы ожидаете, что также будет собрана отладочная версия, не используйте ключ "-o Makefile".
Плагин Qt OCI поддерживает Oracle 9i, 10g и выше. После соединения с сервером Oracle плагин автоматически определяет версию базы данных и активирует соответствующую функциональность.
Возможно соединение с базой данных Oracle без файла tnsnames.ora. Для этого необходимо, чтобы SID базы данных передавался драйверу, как задается имя базы данных и имя ее узла.
Плагин Qt OCI поддерживает аутентификацию, использующую внешние учетные записи (OCI_CRED_EXT). Обычно это означает, что сервер БД будет использовать информацию об авторизации пользователя в операционной системе, а не применять свой механизм аутентификации.
Чтобы это использовать, оставьте поля имени пользователя и пароля пустыми при соединении с QSqlDatabase.
Binary Large Objects (BLOBs) может быть использован для четния и записи, но будьте готовы к тому, что это потребует много памяти. Вы должны использовать впрёд только запросы выборки (select) полей LOB (смотрите QSqlQuery::setForwardOnly()).
Вставка BLOB должна быть совершена либо с помощью подготовленного запроса, где BLOB-ы должны быть ограничены шаблоном, либо с помощью QSqlTableModel, которая использует подготовленные запросы внутри.
Для Oracle 10g всё, что вам нужно, - это "Instant Client Package - Basic" и "Instant Client Package - SDK". Для Oracle до 10g вам необходим стандартный клиент Oracle и SDK пакеты.
Библиотеки Oracle, необходимые для сборки драйвера:
Задайте qmake, где найти заголовочные файлы Oracle и библиотеки, затем запустите make:
Для Oracle версии 9:
cd $QTDIR/src/plugins/sqldrivers/oci qmake "INCLUDEPATH+=$ORACLE_HOME/rdbms/public $ORACLE_HOME/rdbms/demo" "LIBS+=-L$ORACLE_HOME/lib -lclntsh -lwtc9" oci.pro make
Для Oracle версии 10 мы полагаем, что вы установили RPM пакеты Instant Client Package SDK (вы должны настроить соответствующий номер версии):
cd $QTDIR/src/plugins/sqldrivers/oci qmake "INCLUDEPATH+=/usr/include/oracle/10.1.0.3/client/" "LIBS+=-L/usr/lib/oracle/10.1.0.3/client/lib" oci.pro make
При выборе опции "Programmer" в клиенте Oracle, установщик из Oracle Client Installation CD должен установить всё, что необходимо для сборки плагина.
Соберите плагин следующим образом (здесь мы полагаем, что клиент Oracle установлен в C:\oracle):
set INCLUDE=%INCLUDE%;c:\oracle\oci\include set LIB=%LIB%;c:\oracle\oci\lib\msvc cd %QTDIR%\src\plugins\sqldrivers\oci qmake oci.pro nmake
Если вы используете компилятор не от Microsoft, замените nmake на make.
Когда вы запускаете ваше приложение, вам необходимо добавить путь до oci.dll в переменную окружения PATH:
set PATH=%PATH%;c:\oracle\bin
Замечание: Этот плагин базы данных не поддерживается для Windows CE.
ODBC - это общий интерфейс, который позволяет вам соединяться с множеством СУБД. Драйвер QODBC позволяет вам соединяться с "Источником данных ODBC" и получать доступ к имеющимся источникам данных. Заметьте, что вы так же нуждаетесь в установке и настройке драйверов ODBC для "Источника данных ODBC", который установлен на вашей системе. Плагин QODBC позволит вам использовать эти источники данных в ваших Qt приложениях.
Замечание: вы должны использовать родные драйверы, предпочитая их драйверу ODBC, там, где это возможно. Поддержка ODBC может быть использована как обходной путь для баз данных, если родной драйвер не доступен.
На Windows "Источник данных ODBC" должен быть установлен по умолчанию. Для Unix систем есть несколько реализаций, которые должны быть сначала установлены. Заметьте, что каждый клиент, который использует ваше приложение, требует наличия установленного "Источника данных ODBC", в противном случае плагин QODBC не будет работать.
Помните, что при подключении к ODBC данных вы должны ввести имя ODBC источника данных в функцию QSqlDatabase::setDatabaseName(), а не имя БД.
Для работы плагину QODBC нужен совместимый ODBC менеджер драйвера версии 2.0 или позже. Некоторые ODBC драйверы обозначаются версией 2.0, но не поддерживают необходимую функциональность. 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!
[fuzzy]By default, Qt instructs the ODBC driver to behave as an ODBC 2.x driver. However, for some driver-manager/ODBC 3.x-driver combinations (e.g., unixODBC/MaxDB ODBC), telling the ODBC driver to behave as a 2.x driver can cause the driver plugin to have unexpected behavior. To avoid this problem, instruct the ODBC driver to behave as a 3.x driver by setting the connect option "SQL_ATTR_ODBC_VERSION=SQL_OV_ODBC3" before you open your database connection. Note that this will affect multiple aspects of ODBC driver behavior, e.g., the SQLSTATEs. Before setting this connect option, consult your ODBC documentation about behavior differences you can expect.
If you experience very slow access of the ODBC datasource, make sure that ODBC call tracing is turned off in the ODBC datasource manager.
Some drivers don't support scrollable cursors. In that case case only queries in forwardOnly mode can be used successfully.
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.
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.
Some driver managers and drivers don't support UNICODE. To use the QODBC plugin with such drivers it has to be compiled with the Q_ODBC_VERSION_2 defined.
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.
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
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 odbc.pro nmake
Если вы используете компилятор не от Microsoft, замените nmake на make.
Note: This database plugin is not officially supported for Windows CE.
The QPSQL driver supports version 7.3 and higher of the PostgreSQL server. We recommend that you use a client library from version 7.3.15, 7.4.13, 8.0.8, 8.1.4 or more recent as these versions contain security fixes, and as the QPSQL driver might not build with older versions of the client library depending on your platform.
For more information about PostgreSQL visit http://www.postgresql.org.
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.
Binary Large Objects are supported through the BYTEA field type in PostgreSQL server versions >= 7.1.
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 "INCLUDEPATH+=/usr/include/pgsql" "LIBS+=-L/usr/lib -lpq" psql.pro make
После установки Qt, как описано в документе Установка Qt/X11, вам нужно установить плагин в каталог по умолчанию:
cd $QTDIR/src/plugins/sqldrivers/psql make install
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 "INCLUDEPATH+=C:\psql\include" "LIBS+=C:\psql\lib\ms\libpq.lib" psql.pro nmake
Замечание: Этот плагин базы данных не поддерживается для Windows CE.
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.
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 "INCLUDEPATH=$SYBASE/include" "LIBS=-L$SYBASE/lib -lsybdb" make
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 "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.
Замечание: Этот плагин базы данных не поддерживается для Windows CE.
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()).
cd $QTDIR/src/plugins/sqldrivers/db2 qmake "INCLUDEPATH+=$DB2DIR/include" "LIBS+=-L$DB2DIR/lib -ldb2" make
После установки Qt, как описано в документе Установка Qt/X11, вам нужно установить плагин в каталог по умолчанию:
cd $QTDIR/src/plugins/sqldrivers/db2 make install
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 "INCLUDEPATH+=<DB2 home>/sqllib/include" "LIBS+=<DB2 home>/sqllib/lib/db2cli.lib" nmake
Если вы используете компилятор не от Microsoft, замените nmake на make.
Замечание: Этот плагин базы данных не поддерживается для Windows CE.
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.
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()).
In SQLite any column, with the exception of an INTEGER PRIMARY KEY column, may be used to store any type of value. For instance, a column declared as INTEGER may contain an integer value in one row and a text value in the next. This is due to SQLite associating the type of a value with the value itself rather than with the column it is stored in. A consequence of this is that the type returned by QSqlField::type() only indicates the field's recommended type. No assumption of the actual type should be made from this and the type of the individual values should be checked.
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.
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 "INCLUDEPATH+=$SQLITE/include" "LIBS+=-L$SQLITE/lib -lsqlite" make
После установки Qt, как описано в документе Установка Qt/X11, вам нужно установить плагин в каталог по умолчанию:
cd $QTDIR/src/plugins/sqldrivers/sqlite make install
On Windows:
cd %QTDIR%\src\plugins\sqldrivers\sqlite qmake "INCLUDEPATH+=C:\SQLITE\INCLUDE" "LIBS+=C:\SQLITE\LIB\SQLITE3.LIB" sqlite.pro nmake
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.
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.
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.
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(). Пример:
QSqlQuery q; q.exec("execute procedure my_procedure"); q.next(); qDebug() << q.value(0); // outputs the first RETURN/OUT value
Ниже полагается, что InterBase или Firebird установлены в /opt/interbase:
Если вы используете InterBase:
cd $QTDIR/src/plugins/sqldrivers/ibase qmake "INCLUDEPATH+=/opt/interbase/include" "LIBS+=-L/opt/interbase/lib" ibase.pro make
If you are using Firebird, the Firebird library has to be set explicitly:
cd $QTDIR/src/plugins/sqldrivers/ibase qmake "INCLUDEPATH+=/opt/interbase/include" "LIBS+=-L/opt/interbase/lib -lfbclient" ibase.pro make
Ниже полагается, что InterBase или Firebird установлены в C:\interbase:
Если вы используете InterBase:
cd %QTDIR%\src\plugins\sqldrivers\ibase qmake "INCLUDEPATH+=C:\interbase\include" ibase.pro nmake
Если вы используете Firebird, то библиотека Firebird должна устанавливаться явно:
cd %QTDIR%\src\plugins\sqldrivers\ibase qmake "INCLUDEPATH+=C:\interbase\include" "LIBS+=-lfbclient" ibase.pro nmake
Если вы используете компилятор не от Microsoft, замените nmake на make.
Помните, что C:\interbase\bin должен быть в PATH.
Замечание: Этот плагин базы данных не поддерживается для Windows CE.
Вы должны всегда использовать библиотеки клиента, которые были собраны тем же компилятором, который вы используете для своего проекта. Если вы не можете получить описание источника сборки библиотеки клиента самостоятельно, попробуйте удостовериться, что предсобранная библиотека совместима с вашим компилятором, иначе вы получите множество ошибок "undefined symbols". Некоторые компиляторы имеют инструменты для преобразования библиотек, например, Borland предоставляет инструмент COFF2OMF.EXE для преобразования библиотек, которые были собраны в Microsoft Visual C++.
Если компиляция плагина прошла успешно, но он не может быть загружен, убедитесь в том, что следующие требования выполнены:
If you experience plugin load problems and see output like this:
QSqlDatabase: QMYSQL driver not loaded QSqlDatabase: available drivers: QMYSQL
The problem is usually that the plugin had the wrong build key. This might require removing an entry from the plugin cache. Here is some more plugin debugging info.
QSqlDatabase отвечает за закрузку и управление плагинами драйверов баз данных. Когда добавляется база данных (смотри QSqlDatabase::addDatabase()), загружается соответствующий драйвер (используя QSqlDriverPlugin). QSqlDatabase предполагает, что плагин драйвера реализует интерфейсы QSqlDriver и QSqlResult.
QSqlDriver является абстрактным базовым классом, который определяет функционирование SQL драйвера БД. В него входят такие функции, как QSqlDriver::open() и QSqlDriver::close(). QSqlDriver отвечает за подключение к БД, настройку текущего окружения и т.д. Плюс к этому, QSqlDriver может создать объекты QSqlQuery, применяемых для специального взаимодействия с API базы данных. QSqlDatabase переадресует много функций, вызываемых непосредственно из QSqlDriver, который обеспечивает их конкретную реализацию.
QSqlResult - абстрактный базовый класс, который определяет функционирование запросов SQL. Он включает такие конструкции, как SELECT, UPDATE и ALTER TABLE. QSqlResult содержит такие функции, как QSqlResult::next() и QSqlResult::value(). QSqlResult отвечает за отправку запросов к БД, возврат результатов и т.д. QSqlQuery переадресует много функций, вызываемых непосредственно из QSqlResult, который обеспечивает их конкретную реализацию.
QSqlDriver и QSqlResult близко связаны. Когда используется Qt SQL драйвер, оба этих класса должны быть унаследованы в подклассах, причём все абстрактные виртуальные методы каждого класса должны быть реализованы.
Для применения Qt SQL драйвера в качестве плагина (чтобы он был распознан и загружен в Qt во время выполнения программы), он должен использовать макрос Q_EXPORT_PLUGIN2(). Для того, чтобы получить больше информации, прочитайте Как создавать плагины. Вы можете также проверить, как это реализовано в Qt в директориях QTDIR/src/plugins/sqldrivers и QTDIR/src/sql/drivers.
Код ниже можно использовать в качестве основы для SQL драйвера:
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 © 2008 Nokia | Торговые марки | Qt 4.4.3 |
Попытка перевода Qt документации. Если есть желание присоединиться, или если есть замечания или пожелания, то заходите на форум: Перевод Qt документации на русский язык... Люди внесшие вклад в перевод: Команда переводчиков |