Оглавление
Драйверы баз данных SQLМодуль QtSql использует плагины драйверов для взаимодействия с API различных баз данных. Так как API SQL модуля не зависит от баз данных, код, специфичный для определенной БД, содержится в этих драйверах. Некоторые драйвера поставляются с Qt, а другие могут быть добавлены. Исходный код драйверов также предоставляется и может быть использован как модель для написания собственных драйверов. Поддерживаемые базы данныхВ таблице ниже представлен список драйверов, поставляемых с Qt. Due to license incompatibilities with the GPL, not all of the plugins are provided with Open Source Versions of Qt.
SQLite is the in-process database system with the best test coverage and support on all platforms. Oracle via OCI, and PostreSQL and MySQL through either ODBC or a native driver are well-tested on Windows and Linux. The completeness of the support for other systems depends on the availability and quality of client libraries. Замечание: для сборки плагина драйвера вам нужно иметь соответствующую клиентскую библиотеку для вашей системы управления базами данных (СУБД). Это обеспечивает доступ к 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> как плагин для подключения во время выполнения программы. Доступные значения для <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> для сборки драйвера в виде плагина. Для дополнительной информации о необходимых библиотеках смотрите разделы ниже. Сборка плагинов вручнуюQMYSQL для MySQL 4 и вышеПоддержка хранимых процедур в QMYSQLВ 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); // 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 "INCLUDEPATH+=/usr/local/include" "LIBS+=-L/usr/local/lib -lmysqlclient_r" mysql.pro make After installing Qt, as described in the Installing Qt for X11 Platforms document, you also need to install the plugin in the standard location: 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 "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". How to build the MySQL driver for MinGW usersThe following steps have been used successfully for WinXP SP3. In this example, Qt 4.6.2 is shown.
QOCI для Oracle Call Interface (OCI)Общая информация о OCI плагинеПлагин Qt OCI поддерживает Oracle 9i, 10g и выше. После соединения с сервером Oracle плагин автоматически определяет версию базы данных и активирует соответствующую функциональность. Возможно соединение с базой данных Oracle без файла tnsnames.ora. Для этого необходимо, чтобы SID базы данных передавался драйверу, как задается имя базы данных и имя ее узла. OCI авторизация пользователяПлагин Qt OCI поддерживает аутентификацию, использующую внешние учетные записи (OCI_CRED_EXT). Обычно это означает, что сервер БД будет использовать информацию об авторизации пользователя в операционной системе, а не применять свой механизм аутентификации. Чтобы это использовать, оставьте поля имени пользователя и пароля пустыми при соединении с QSqlDatabase. Поддержка OCI BLOB/LOBBinary Large Objects (BLOBs) может быть использован для четния и записи, но будьте готовы к тому, что это потребует много памяти. Вы должны использовать впрёд только запросы выборки (select) полей LOB (смотрите QSqlQuery::setForwardOnly()). Вставка BLOB должна быть совершена либо с помощью подготовленного запроса, где BLOB-ы должны быть ограничены шаблоном, либо с помощью QSqlTableModel, которая использует подготовленные запросы внутри. Как собрать OCI плагин под Unix и Mac OS XДля 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 -lclntsh" oci.pro make Note: If you are using the Oracle Instant Client package, you will need to set LD_LIBRARY_PATH when building the OCI SQL plugin and when running an applicaiton that uses the OCI SQL plugin. You can avoid this requirement by setting and RPATH and listing all of the libraries to link to. Вот пример: configure -I /usr/include/oracle/10.1.0.3/client -L /usr/lib/oracle/10.1.0.3/client/lib -R /usr/lib/oracle/10.1.0.3/client/lib -lclntsh -lnnz10 make If you wish to build the OCI plugin manually with this method the procedure looks like this: 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 -Wl,-rpath,/usr/lib/oracle/10.1.0.3/client/lib -lclntsh -lnnz10" oci.pro make Как собрать OCI плагин под WindowsChoosing the option "Programmer" in the Oracle Client Installer from the Oracle Client Installation CD is generally sufficient to build the plugin. For some versions of Oracle Client, you may also need to select the "Call Interface (OCI)" option if it is available. Соберите плагин следующим образом (здесь мы полагаем, что клиент 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. QODBC для Open Database Connectivity (ODBC)Общая информация о ODBC плагине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. Поддержка хранимых процедур в ODBCWith 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. Поддержка Unicode в ODBCThe 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. Как собрать ODBC плагин под Unix и Mac OS XIt 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 плагин под WindowsThe 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. QPSQL для PostgreSQL (Версия 7.3 и выше)Общая информация о QPSQL драйвере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. Поддержка Unicode в QPSQLThe 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 в QPSQLBinary Large Objects are supported through the BYTEA field type in PostgreSQL server versions >= 7.1. Как собрать QPSQL плагин под Unix и Mac OS XYou 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 After installing Qt, as described in the Installing Qt for X11 Platforms document, you also need to install the plugin in the standard location: cd $QTDIR/src/plugins/sqldrivers/psql make install Как собрать QPSQL плагин под WindowsInstall the appropriate PostgreSQL developer libraries for your compiler. 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 Users of MinGW may wish to consult the following online document: PostgreSQL MinGW/Native Windows. Замечание: Этот плагин базы данных не поддерживается для Windows CE. QTDS для Sybase Adaptive ServerNote: TDS is no longer used by MS Sql Server, and is superceded by ODBC. QTDS устарел начиная с Qt 4.7. Общая информация о QTDSIt 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. How to Build the QTDS Plugin on Unix and Mac OS XUnder 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 Как собрать QDTS плагин под WindowsYou 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. QDB2 для IBM DB2 (Версия 7.1 и выше)Общая информация о QDB2The 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 Xcd $QTDIR/src/plugins/sqldrivers/db2 qmake "INCLUDEPATH+=$DB2DIR/include" "LIBS+=-L$DB2DIR/lib -ldb2" make After installing Qt, as described in the Installing Qt for X11 Platforms document, you also need to install the plugin in the standard location: cd $QTDIR/src/plugins/sqldrivers/db2 make install Как собрать QDB2 плагин под WindowsThe 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. QSQLITE2 SQLite версия 2The 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 и выше)Общая информация о QSQLITEThe 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. Как собрать 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 "INCLUDEPATH+=$SQLITE/include" "LIBS+=-L$SQLITE/lib -lsqlite" make After installing Qt, as described in the Installing Qt for X11 Platforms document, you also need to install the plugin in the standard location: cd $QTDIR/src/plugins/sqldrivers/sqlite make install В Windows: cd %QTDIR%\src\plugins\sqldrivers\sqlite qmake "INCLUDEPATH+=C:\SQLITE\INCLUDE" "LIBS+=C:\SQLITE\LIB\SQLITE3.LIB" sqlite.pro nmake Совместимость файловых форматов QSQLITESQLite 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. QSYMSQL for SQLite (Version 3 and Above) with Symbian SQL DatabaseGeneral Information about QSYMSQLQSYMSQL driver enables clients to access the native Symbian database engine (?Symbian SQL?) through the QtSQL API. The main difference to QSQLITE is that, with Symbian SQL database client can specify a set of access control policies when creating a new database. It uses Symbian SQL security policy definitions within open() call (security policy is defined with in the connection options parameters). Symbian RSqlSecurityPolicy class is a container for the security policies for a shared SQL database. The container can contain: security policies that apply to the database. security policies that apply to individual database objects, i.e. database tables. For the database, you use RSqlSecurityPolicy::SetDbPolicy() to apply a separate security policy to: the database schema. read activity on the database. write activity on the database. For database tables, you use RSqlSecurityPolicy::SetPolicy() to apply a separate security policy to: write activity on each named database table. read activity on each named database table. More information about Symbian SQL and RSqlSecurityPolicy class reference about policy definitions, can be found from Forum Nokia Library: http://library.developer.nokia.com/. Example of setting Security Policy: Connection options hold definition for security policies and all parameters that does not contain "POLICY_" will be passed to RSqlDatabase. Policy will be filled according to parsed values. Value in database wide parameters starts by definition which can be vendorId or secureId. These come directly from TSecurityPolicy class in Symbian. POLICY_DB_DEFAULT Default security policy which will be used for the database and all database objects. POLICY_DB_DEFAULT must be defined before any other policy definitions can be used. POLICY_DB_READ Read database security policy. An application with read database security policy can read from database. POLICY_DB_WRITE: Write database security policy. An application with write database security policy can write to database. POLICY_DB_SCHEMA: Schema database security policy. An application with schema database security policy can modify the database schema, write to database, read from database. Format: POLICY_DB_DEFAULT=cap1,cap2,cap3,cap4,cap5,cap6,cap7 (Up to 7 capabilities) POLICY_DB_READ=cap1,cap2,cap3,cap4,cap5,cap6,cap7 (Up to 7 capabilities) POLICY_DB_WRITE=vendorid,cap1,cap2,cap3 (Vendor ID and up to 3 capabilities) POLICY_DB_SCHEMA=secureid,cap1,cap2,cap3 (Secure ID and up to 3 capabilities) Table policies does not support schema policy as database level does. Table specific parameters would be as: POLICY_TABLE_WRITE=tablename,cap1,cap2,cap3,cap4,cap5,cap6,cap7 POLICY_TABLE_READ=tablename,cap1,cap2,cap3,cap4,cap5,cap6,cap7 Vendor Id and Secure id format: vid[0x12345678] (Hex) sid[0x12345678] (Hex) Examples: Setting default policy: QSqlDatabase database = QSqlDatabase::addDatabase("QSYMSQL", "MyConnection"); database.setConnectOptions("POLICY_DB_DEFAULT=ReadDeviceData"); database.setDatabaseName("[12345678]myDatabase"); bool ok = database.open(); Setting POLICY_DB_WRITE: QSqlDatabase database = QSqlDatabase::addDatabase("QSYMSQL", "MyConnection"); database.setConnectOptions("POLICY_DB_DEFAULT=None; POLICY_DB_WRITE=sid[0x12345678], WriteDeviceData"); database.setDatabaseName("[12345678]myDatabase"); bool ok = database.open(); FOREIGN KEY: Enabling foreign key support from underlying SQLite add: "foreign_keys = ON" to your connection options string. This will be passes to SQLite. Foreign key Example: QSqlDatabase database = QSqlDatabase::addDatabase("QSYMSQL", "MyConnection"); database.setDatabaseName("[12345678]myDatabase"); database.setConnectOptions("foreign_keys = ON"); bool ok = database.open(); How to Build the QSYMSQL PluginBuilding QSYMSQL requires Symbian SDK. The build sequence is similar to the QSQLITE plugin with installing the plugin in the standard location. Build sequence: >cd sf QIBASE для Borland InterBaseОбщая информация о QIBASEThe 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. Firebird must be used with a server configuration. 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. Поддержка Unicode в QIBASE и кодировка текста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. Хранимые процедуры в QIBASEInterBase/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 Как собрать QIBASE плагин под Unix и Mac OS XНиже полагается, что 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 Как собрать QIBASE плагин под WindowsНиже полагается, что 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++. Если компиляция плагина прошла успешно, но он не может быть загружен, убедитесь в том, что следующие требования выполнены:
Make sure you have followed the guide to Deploying Plugins. 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. Как написать собственный драйвер БД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() const { 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); } }; |
Попытка перевода Qt документации. Если есть желание присоединиться, или если есть замечания или пожелания, то заходите на форум: Перевод Qt документации на русский язык... Люди внесшие вклад в перевод: Команда переводчиков |