SQL数据库驱动程序

SQL Database Drivers

SQL数据库驱动程序

The Qt SQL 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.

QtSQL模块使用驱动程序插件与不同的数据库API进行通信。由于Qt的SQL模块API与数据库无关,所有特定于数据库的代码都包含在这些驱动程序中。Qt提供了几个驱动程序,还可以添加其他驱动程序。提供了驱动程序源代码,可以用作编写自己的驱动程序的模型。

Supported Databases

支持的数据库

The table below lists the drivers included with Qt:

下表列出了Qt中包含的驱动程序:

Driver name

DBMS

QDB2

IBM DB2 (version 7.1 and above)

IBM DB2(7.1及更高版本)

#QIBASE

Borland InterBase / Firebird

QMYSQL / MARIADB

MySQL or MariaDB (version 5.6 and above)

MySQL或MariaDB(5.6及以上版本)

QOCI

Oracle Call Interface Driver (version 12.1 and above)

Oracle调用接口驱动程序(12.1及以上版本)

QODBC

Open Database Connectivity (ODBC) - Microsoft SQL Server and other ODBC-compliant databases

开放式数据库连接(ODBC)-Microsoft SQL Server和其他符合ODBC的数据库

QPSQL

PostgreSQL (versions 7.3 and above)

PostgreSQL(7.3及以上版本)

QSQLITE

SQLite version 3

SQLite版本3

SQLite is the in-process database system with the best test coverage and support on all platforms. Oracle via OCI, PostgreSQL, 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.

SQLite是在所有平台上具有最佳测试覆盖率和支持的进程内数据库系统。Oracle通过OCI、PostgreSQL和MySQL通过ODBC或本机驱动程序在Windows和Linux上进行了良好的测试。对其他系统的支持的完整性取决于客户端库的可用性和质量。

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. Also make sure to install the correct database libraries for your Qt architecture (32 or 64 bit).
注意:要构建驱动程序插件,您需要为数据库管理系统(DBMS)提供适当的客户端库。这提供了对DBMS公开的API的访问,并且通常随附。大多数安装程序还允许您安装“开发库”,而这些正是您所需要的。这些库负责与DBMS的低级通信。还要确保为您的Qt体系结构(32或64位)安装正确的数据库库。
Note: When using Qt under Open Source terms but with a proprietary database, verify the client library's license compatibility with the LGPL.
注意:当根据开源条款使用Qt但使用专有数据库时,请验证客户端库与LGPL的许可证兼容性。

Building the Drivers

构建驱动程序

Compile Qt with a specific driver

使用特定驱动程序编译Qt

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:

Qt配置脚本尝试自动检测计算机上可用的客户端库。运行configure-help查看可以构建哪些驱动程序。您应该得到类似的输出:

[...]

Database options:

  -sql-<driver> ........ Enable SQL <driver> plugin. Supported drivers:
                         db2 ibase mysql oci odbc psql sqlite
                         [all auto]
  -sqlite .............. Select used sqlite [system/qt]

[...]

The configure script cannot detect the necessary libraries and include files if they are not in the standard paths, so it may be necessary to specify these paths using either driver-specific include and library path variables or CMAKE_INCLUDE_PATH and CMAKE_LIBRARY_PATH. For example, if your MySQL files are installed in C:\mysql-connector-c-6.1.11-winx64 on Windows, then pass the following parameter to double-dash part of configure line:

如果必要的库和包含文件不在标准路径中,则配置脚本无法检测到它们,因此可能需要使用驱动程序特定的包含和库路径变量或CMAKE_include_path和CMAKE_library_path来指定这些路径。例如,如果您的MySQL文件安装在Windows上的C:\mysql-connector-c-6.1.11-winx64中,则将以下参数传递到配置行的双引号部分:

C:\Qt\6.0.0\Src\configure.bat -sql-mysql -- -DMySQL_INCLUDE_DIR="C:\mysql-8.0.22-winx64\include" -DMySQL_LIBRARY="C:\mysql-8.0.22-winx64\lib\libmysql.lib"
Configure summary:

...
Qt Sql Drivers:
  DB2 (IBM) .............................. no
  InterBase .............................. no
  MySql .................................. yes
  OCI (Oracle) ........................... no
  ODBC ................................... yes
  PostgreSQL ............................. no
  SQLite ................................. yes
    Using system provided SQLite ......... no
...

When you configure drivers in the manner described above, CMake skips any dependency checks and uses the provided paths as is. This is especially useful if the package provides its own set of system libraries that should not be recognized by the build routine.

当您以上述方式配置驱动程序时,CMake会跳过任何依赖项检查,并按原样使用所提供的路径。如果包提供了自己的一组系统库,而这些库不应被构建例程识别,则这一点尤其有用。

In some cases it's more convenient to use CMAKE_INCLUDE_PATH and CMAKE_LIBRARY_PATH variables to locate required libraries. You should prefer this method if module needs to set properties for the provided target libraries (e.g. this is required for PostgreSQL and SQLite). For example, you can do this as follows, to locate MySQL:

在某些情况下,使用CMAKE_INCLUDE_PATH和CMAKE_LIBRARY_PATH变量来查找所需的库会更方便。如果模块需要为提供的目标库设置属性(例如,PostgreSQL和SQLite需要这样做),应该首选此方法。例如,可以按如下方式进行定位MySQL:

C:\Qt\6.0.0\Src\configure.bat -sql-mysql -- -DCMAKE_INCLUDE_PATH="C:\mysql-8.0.22-winx64\include" -DCMAKE_LIBRARY_PATH="C:\mysql-8.0.22-winx64\lib"
Configure summary:

...
Qt Sql Drivers:
  DB2 (IBM) .............................. no
  InterBase .............................. no
  MySql .................................. yes
  OCI (Oracle) ........................... no
  ODBC ................................... yes
  PostgreSQL ............................. no
  SQLite ................................. yes
    Using system provided SQLite ......... no
...

The particulars for each driver are explained below.

每个驱动的详细信息如下所述。

Note: If something goes wrong and you want CMake to recheck your available drivers, you might need to remove CMakeCache.txt from the build directory.
注意:如果出现问题,并且您希望CMake重新检查可用的驱动程序,则可能需要从构建目录中删除CMakeCache.txt。

Compile only a specific sql driver

仅编译特定的sql驱动程序

A typical qt-cmake run (in this case to configure for MySQL) looks like this:

典型的qt-cmake运行(在本例中为MySQL配置)如下所示:

C:\Qt\6.0.0\mingw81_64\bin\qt-cmake -G Ninja C:\Qt\6.0.0\Src\qtbase\src\plugins\sqldrivers -DMySQL_INCLUDE_DIR="C:\mysql-8.0.22-winx64\include" -DMySQL_LIBRARY="C:\mysql-8.0.22-winx64\lib\libmysql.lib" -DCMAKE_INSTALL_PREFIX="C:\Qt\6.0.0\mingw81_64"
Configure summary:

Qt Sql Drivers:
  DB2 (IBM) .............................. no
  InterBase .............................. no
  MySql .................................. yes
  OCI (Oracle) ........................... no
  ODBC ................................... yes
  PostgreSQL ............................. no
  SQLite ................................. yes
    Using system provided SQLite ......... no

-- Configuring done
-- Generating done
-- Build files have been written to: C:/build-qt6-sqldrivers
Note: As mentioned in Compile Qt with a specific driver, if the driver could not be found or is not enabled, start over by removing CMakeCache.txt.
注意:如使用特定驱动程序编译Qt中所述,如果找不到驱动程序或未启用驱动程序,请通过删除CMakeCache.txt重新启动。

Due to the practicalities of dealing with external dependencies, only the SQLite plugin is shipped with binary builds of Qt. Binary builds of Qt for Windows also include the ODBC plugin. To be able to add additional drivers to the Qt installation without re-building all of Qt, it is possible to configure and build the qtbase/src/plugins/sqldrivers directory outside of a full Qt build directory. Note that it is not possible to configure each driver separately, only all of them at once. Drivers can be built separately, though.

由于处理外部依赖关系的实用性,Qt的二进制构建只附带了SQLite插件。Qt for Windows的二进制版本也包括ODBC插件。为了能够在不重新构建所有Qt的情况下向Qt安装添加额外的驱动程序,可以在完整的Qt构建目录之外配置和构建qtbase/src/plugins/sqldrivers目录。请注意,不可能单独配置每个驱动程序,只能同时配置所有驱动程序。不过,驱动程序可以单独构建。

Note: You need to specify CMAKE_INSTALL_PREFIX, if you want to install plugins after the build is finished.
注意:如果您想在构建完成后安装插件,则需要指定CMAKE_INSTALL_PREFIX。

Driver Specifics

驱动程序详细信息

QMYSQL for MySQL or MariaDB 5.6 and higher

适用于MySQL或MariaDB 5.6及更高版本的QMYSQL

MariaDB is a fork of MySQL intended to remain free and open-source software under the GNU General Public License. MariaDB intended to maintain high compatibility with MySQL, ensuring a drop-in replacement capability with library binary parity and exact matching with MySQL APIs and commands. Therefore the plugin for MySQL and MariaDB are combined into one Qt plugin.

MariaDB是MySQL的一个分支,旨在根据GNU通用公共许可证保持自由和开源软件。MariaDB旨在保持与MySQL的高度兼容性,确保库二进制奇偶校验的替换能力下降,并与MySQL API和命令精确匹配。因此,MySQL和MariaDB的插件被合并为一个Qt插件。

QMYSQL Stored Procedure Support
QMYSQL存储过程支持

MySQL 5 has 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().

MySQL 5在SQL级别支持存储过程,但没有控制IN、OUT和INOUT参数的API。因此,必须使用SQL命令而不是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:

访问OUT值的源代码:

QSqlQuery q;
q.exec("call qtestproc (@outval1, @outval2)");
q.exec("select @outval1, @outval2");
if (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.
注意:@outval1和@outval2是当前连接的本地变量,不会受到从其他主机或连接发送的查询的影响。
Embedded MySQL Server
嵌入式MySQL服务器

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.

MySQL嵌入式服务器是普通客户端库的一个替代品。对于嵌入式MySQL服务器,MySQL服务器不需要使用MySQL功能。

To use the embedded MySQL server, simply link the Qt plugin to libmysqld instead of libmysqlclient. This can be done by adding -DMySQL_LIBRARY=<path/to/mysqld/>libmysqld.<so|lib|dylib> to the configure command line.

要使用嵌入式MySQL服务器,只需将Qt插件链接到libmysqld,而不是libmysqlclient。这可以通过添加-DMySQL_LIBRARY=<path/to/mysqld/>libmysqld.<so|lib|dylib>到configure命令行。

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

有关MySQL嵌入式服务器的更多信息,请参阅MySQL文档“libmysqld,嵌入式MySQL服务器库”一章。

How to Build the QMYSQL Plugin on Unix and macOS
如何在Unix和macOS上构建QMYSQL插件

You need the MySQL / MariaDB header files, as well as the shared library libmysqlclient.<so|dylib> / libmariadb.<so|dylib>. Depending on your Linux distribution, you may need to install a package which is usually called "mysql-devel" or "mariadb-devel".

您需要MySQL/MariaDB头文件,以及共享库libmysqlclient.<so|dylib> / libmariadb.<so|dylib>。根据您的Linux发行版,您可能需要安装一个通常称为“mysql-devel”或“mariadb-devel”的软件包。

Tell qt-cmake where to find the MySQL / MariaDB header files and shared libraries (here it is assumed that MySQL / MariaDB is installed in /usr/local) and build:

告诉qt-cmake在哪里可以找到MySQL/MariaDB头文件和共享库(这里假设MySQL/MMariaDB安装在/usr/local中)并构建:

mkdir build-sqldrivers
cd build-sqldrivers

qt-cmake -G Ninja <qt_installation_path>/Src/qtbase/src/plugins/sqldrivers -DCMAKE_INSTALL_PREFIX=<qt_installation_path>/<platform> -DMySQL_INCLUDE_DIR="/usr/local/mysql/include" -DMySQL_LIBRARY="/usr/local/mysql/lib/libmysqlclient.<so|dylib>"
cmake --build .
cmake --install .
How to Build the QMYSQL Plugin on Windows
如何在Windows上构建QMYSQL插件

You need to get the MySQL installation files (e.g. mysql-installer-web-community-8.0.22.0.msi or mariadb-connector-c-3.1.11-win64.msi). Run the installer, select custom installation and install the MySQL C Connector which matches your Qt installation (x86 or x64). After installation check that the needed files are there:

您需要获取MySQL安装文件(例如,mysql-installer-web-community-8.0.22.0.msi或mariadb-connector-c-3.1.11-win64.msi)。运行安装程序,选择自定义安装并安装与您的Qt安装相匹配的MySQL C连接器(x86或x64)。安装后,检查所需的文件是否存在:

  • <MySQL dir>/lib/libmysql.lib

  • <MySQL dir>/lib/libmysql.dll

  • <MySQL dir>/include/mysql.h

and for MariaDB

  • <MariaDB dir>/lib/libmariadb.lib

  • <MariaDB dir>/lib/libmariadb.dll

  • <MariaDB dir>/include/mysql.h

Note: As of MySQL 8.0.19, the C Connector is no longer offered as a standalone installable component. Instead, you can get mysql.h and libmysql.* by installing the full MySQL Server (x64 only) or the MariaDB C Connector.
注意:从MySQL 8.0.19开始,C连接器不再作为独立的可安装组件提供。相反,您可以通过安装完整的mysql服务器(仅x64)或MariaDB C连接器来获得mysql.h和libmysql.*。

Build the plugin as follows (here it is assumed that <MySQL dir> is C:\mysql-8.0.22-winx64):

按照如下方式构建插件(这里假设<MySQL目录>是C:\MySQL-8.0.22-winx64):

mkdir build-sqldrivers
cd build-sqldrivers

qt-cmake -G Ninja <qt_installation_path>\Src\qtbase\src\plugins\sqldrivers -DCMAKE_INSTALL_PREFIX=<qt_installation_path>\<platform> -DMySQL_INCLUDE_DIR="C:\mysql-8.0.22-winx64\include" -DMySQL_LIBRARY="C:\mysql-8.0.22-winx64\lib\libmysql.lib"
cmake --build .
cmake --install .

When you distribute your application, remember to include libmysql.dll / libmariadb.dll in your installation package. It must be placed in the same folder as the application executable. libmysql.dll additionally needs the MSVC runtime libraries which can be installed with vcredist.exe

分发应用程序时,请记住在安装包中包含libmysql.dll/libmariadb.dll。它必须与应用程序可执行文件放在同一文件夹中。libmysql.dll还需要MSVC运行时库,这些库可以与vcredit.exe一起安装

QOCI for the Oracle Call Interface (OCI)

Oracle调用接口(OCI)的QOCI

The Qt OCI plugin supports connecting to Oracle database as determined by the version of the instant client used. This is dependent on what Oracle indicates it supports. The plugin will auto-detect the database version and enable features accordingly.

Qt OCI插件支持连接到Oracle数据库,这取决于所使用的即时客户端的版本。这取决于Oracle表示它支持什么。该插件将自动检测数据库版本并相应地启用功能。

It's possible to connect to a Oracle database without a tnsnames.ora file. This requires that the database SID is passed to the driver as the database name, and that a hostname is given.

可以在没有tnsnames.ora文件的情况下连接到Oracle数据库。这需要将数据库SID作为数据库名称传递给驱动程序,并提供主机名。

OCI User Authentication
OCI用户身份验证

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.

Qt OCI插件支持使用外部凭据(OCI_CRED_EXT)进行身份验证。通常,这意味着数据库服务器将使用操作系统提供的用户身份验证,而不是其自己的身份验证机制。

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

打开与QSqlDatabase的连接以使用外部凭据身份验证时,请将用户名和密码留空。

OCI BLOB/LOB Support
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()).

二进制大对象(BLOBs)可以读写,但要注意这个过程可能需要大量内存。您应该使用仅向前查询来选择LOB字段(请参见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.

插入BLOB应该使用一个预先准备好的查询来完成,其中BLOB绑定到占位符,或者使用QSqlTableModel,它在内部使用一个事先准备好的询问来完成。

How to Build the OCI Plugin on Unix and macOS
如何在Unix和macOS上构建OCI插件

All you need is the " - Basic" and "Instant Client Package - SDK".

您所需要的只是“-Basic”和“Instant Client Package-SDK”。

Oracle library files required to build the driver:

生成驱动程序所需的Oracle库文件:

  • libclntsh.<so|dylib> (all versions)

  • libclntsh<so|dylib>(所有版本)

Tell qt-cmake where to find the Oracle header files and shared libraries and build.

告诉qt-cmake在哪里可以找到Oracle头文件和共享库并进行构建。

We assume that you installed the RPM packages of the Instant Client Package SDK (you need to adjust the version number accordingly):

我们假设您安装了Instant Client Package SDK的RPM软件包(您需要相应地调整版本号):

mkdir build-sqldrivers
cd build-sqldrivers

qt-cmake -G Ninja <qt_installation_path>/Src/qtbase/src/plugins/sqldrivers -DCMAKE_INSTALL_PREFIX=<qt_installation_path>/<platform> -DOracle_INCLUDE_DIR="/usr/include/oracle/21/client64" -DOracle_LIBRARY="/usr/lib/oracle/21/client64/lib/libclntsh.<so|dylib>"
cmake --build .
cmake --install .
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 application that uses the OCI SQL plugin.
注意:如果您使用的是Oracle Instant Client软件包,则在构建OCI SQL插件时,以及在运行使用OCI SQL的应用程序时,都需要设置LD_LIBRARY_PATH。
How to Build the OCI Plugin on Windows
如何在Windows上构建OCI插件

Choosing 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客户端安装CD中选择Oracle客户端安装程序中的选项“Programmer”通常足以构建插件。对于某些版本的Oracle客户端,您可能还需要选择“调用接口(OCI)”选项(如果可用)。

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

按如下方式构建插件(这里假设Oracle Client安装在C:\Oracle中,SDK安装在C:\Oracle\SDK中):

mkdir build-sqldrivers
cd build-sqldrivers
qt-cmake -G Ninja <qt_installation_path>\Src\qtbase\src\plugins\sqldrivers -DCMAKE_INSTALL_PREFIX=<qt_installation_path>\<platform> -DOracle_INCLUDE_DIR="C:\oracle\sdk\include" -DOracle_LIBRARY="C:\oracle\oci.lib"
cmake --build .
cmake --install .

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

运行应用程序时,还需要将oci.lib路径添加到path环境变量中:

set PATH=%PATH%;C:\oracle

QODBC for Open Database Connectivity (ODBC)

用于开放数据库连接(ODBC)的QODBC

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.

ODBC是一个通用接口,允许使用通用接口连接到多个DBMS。QODBC驱动程序允许您连接到ODBC驱动程序管理器并访问可用的数据源。请注意,还需要为系统上安装的ODBC驱动程序管理器安装和配置ODBC驱动程序。QODBC插件允许您在Qt应用程序中使用这些数据源。

Note: You should use the native driver, if it is available, instead of the ODBC driver. ODBC support can be used as a fallback for compliant databases if no native driver is available.
注意:如果本机驱动程序可用,应该使用它,而不是ODBC驱动程序。如果没有本机驱动程序可用,ODBC支持可以用作兼容数据库的后备措施。

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 end user of your application is required to have an ODBC driver manager installed, otherwise the QODBC plugin will not work.

在Windows上,默认情况下应安装ODBC驱动程序管理器。对于Unix系统,有一些实现必须首先安装。请注意,应用程序的每个最终用户都需要安装ODBC驱动程序管理器,否则QODBC插件将无法工作。

When connecting to an ODBC datasource, you should pass the name of the ODBC datasource to the QSqlDatabase::setDatabaseName() function, rather than the actual database name.

当连接到ODBC数据源时,应该将ODBC数据源的名称传递给QSqlDatabase::setDatabaseName()函数,而不是实际的数据库名称。

The QODBC Plugin needs an ODBC compliant driver manager version 2.0 or later. 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 do not like this behavior, you can remove the #define ODBC_CHECK_DRIVER line from the file qsql_odbc.cpp. Do this at your own risk!

QODBC插件需要符合ODBC的驱动程序管理器2.0版或更高版本。一些ODBC驱动程序声称兼容2.0版本,但并没有提供所有必要的功能。因此,QODBC插件在建立连接后检查数据源是否可以使用,如果检查失败,则拒绝工作。如果不喜欢这种行为,可以从文件qsql_odbc.cpp中删除#define ODBC_CHECK_DRIVER行。这样做的风险自负!

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.

默认情况下,Qt指示ODBC驱动程序以ODBC 2.x驱动程序的方式运行。然而,对于某些驱动程序管理器/ODBC3.x驱动程序组合(例如,unixODBC/MaxDB-ODBC),告诉ODBC驱动程序以2.x驱动程序的方式运行可能会导致驱动程序插件出现意外行为。要避免此问题,请在打开数据库连接之前,通过设置连接选项“SQL_ATTR_ODBC_VERSION=SQL_OV_ODBC3”,指示ODBC驱动程序作为3.x驱动程序运行。请注意,这将影响ODBC驱动程序行为的多个方面,例如SQLSTATE。在设置此连接选项之前,请查阅ODBC文档,了解可能出现的行为差异。

When using the SAP HANA database, the connection has to be established using the option "SCROLLABLERESULT=TRUE", as the HANA ODBC driver does not provide scrollable results by default, e.g.:

使用SAP HANA数据库时,必须使用选项“SCROLLABLERESULT=TRUE”建立连接,因为HANA ODBC驱动程序默认情况下不提供可滚动的结果,例如:

QSqlDatabase db = QSqlDatabase::addDatabase("QODBC");
QString connectString = QStringLiteral(
    "DRIVER=/path/to/installation/libodbcHDB.so;"
    "SERVERNODE=hostname:port;"
    "UID=USER;"
    "PWD=PASSWORD;"
    "SCROLLABLERESULT=true");
db.setDatabaseName(connectString);

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数据源的访问非常缓慢,请确保在ODBC数据源管理器中关闭ODBC调用跟踪。

Some drivers do not support scrollable cursors. In that case, only queries in forwardOnly mode can be used successfully.

有些驱动程序不支持可滚动光标。在这种情况下,只能成功使用forwardOnly模式下的查询。

ODBC Stored Procedure Support
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().

对于Microsoft SQL Server,只有使用QSqlQuery::setForwardOnly()将查询的仅转发模式设置为向前查询时,才能访问使用return语句或返回多个结果集的存储过程返回的结果集。

// 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.
注意:存储过程的return语句返回的值将被丢弃。
ODBC Unicode Support
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.

如果定义了UNICODE,QODBC插件将使用Unicode API。在基于Windows NT的系统上,这是默认设置。请注意,ODBC驱动程序和DBMS也必须支持Unicode。

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

对于Oracle 9 ODBC驱动程序(Windows),有必要在ODBC驱动程序管理器中检查“SQL_WCHAR支持”,否则Oracle将把所有Unicode字符串转换为本地8位。

How to Build the ODBC Plugin on Unix and macOS
如何在Unix和macOS上构建ODBC插件

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.

建议使用unixODBC。可以在上找到最新版本和ODBC驱动程序http://www.unixodbc.org.您需要unixODBC头文件和共享库。

Tell qt-cmake where to find the unixODBC header files and shared libraries (here it is assumed that unixODBC is installed in /usr/local/unixODBC) and build:

告诉qt-cmake在哪里可以找到unixODBC头文件和共享库(这里假设unixODBC安装在/usr/local/unixODBC中)并构建:

mkdir build-sqldrivers
cd build-sqldrivers

qt-cmake -G Ninja <qt_installation_path>/Src/qtbase/src/plugins/sqldrivers -DCMAKE_INSTALL_PREFIX=<qt_installation_path>/<platform> -DODBC_INCLUDE_DIR="/usr/local/unixODBC/include" -DODBC_LIBRARY="/usr/local/unixODBC/lib/libodbc.<so|dylib>"
cmake --build .
cmake --install .
How to Build the ODBC Plugin on Windows
如何在Windows上构建ODBC插件

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

ODBC头和包含文件应该已经安装在正确的目录中。只需要按照如下方式构建插件:

mkdir build-sqldrivers
cd build-sqldrivers

qt-cmake -G Ninja <qt_installation_path>\Src\qtbase\src\plugins\sqldrivers -DCMAKE_INSTALL_PREFIX=<qt_installation_path>\<platform>
cmake --build .
cmake --install .

QPSQL for PostgreSQL (Version 7.3 and Above)

用于PostgreSQL的QPSQL(7.3版及更高版本)

The QPSQL driver supports version 7.3 and higher of the PostgreSQL server.

QPSQL驱动程序支持PostgreSQL服务器的7.3版及更高版本。

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

关于PostgreSQL的更多信息,可以查阅http://www.postgresql.org.

QPSQL Unicode Support
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.

QPSQL驱动程序会自动检测您要连接的PostgreSQL数据库是否支持Unicode。如果服务器支持,则会自动使用Unicode。请注意,驱动程序仅支持UTF-8编码。如果数据库使用任何其他编码,则必须使用Unicode转换支持编译服务器。

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.

Unicode支持是在PostgreSQL 7.1版本中引入的,只有在服务器和客户端库都使用多字节支持编译的情况下,它才会起作用。有关如何设置支持多字节的PostgreSQL服务器的更多信息,请参阅《PostgreSQL管理员指南》第5章。

QPSQL Case Sensitivity
QPSQL区分大小写

PostgreSQL databases will only respect case sensitivity if the table or field name is quoted when the table is created. So for example, a SQL query such as:

如果在创建表时用双引号包括表或字段名称,PostgreSQL数据库将只区分大小写。例如,SQL查询,例如:

CREATE TABLE "testTable" ("id" INTEGER);

will ensure that it can be accessed with the same case that was used. If the table or field name is not quoted when created, the actual table name or field name will be lower-case. When QSqlDatabase::record() or QSqlDatabase::primaryIndex() access a table or field that was unquoted when created, the name passed to the function must be lower-case to ensure it is found. For example:

将确保可以使用与所使用的案例相同的案例来访问它。如果创建时未使用双引号包括表或字段名,则实际的表名或字段名将使用小写。当QSqlDatabase::record()或QSqlDatabase::primaryIndex()访问创建时未使用双引号包括表或字段时,传递给函数的名称必须是小写,以确保找到它。例如:

QString tableString("testTable");
QSqlQuery q;
// Create table query is not quoted, therefore it is mapped to lower case
q.exec(QString("CREATE TABLE %1 (id INTEGER)").arg(tableString));
// Call toLower() on the string so that it can be matched
QSqlRecord rec = database.record(tableString.toLower());
QPSQL Forward-only query support

QPSQL仅向前查询支持

To use forward-only queries, you must build the QPSQL plugin with PostreSQL client library version 9.2 or later. If the plugin is built with an older version, then forward-only mode will not be available - calling QSqlQuery::setForwardOnly() with true will have no effect.

要使用仅向前查询,必须使用PostreSQL客户端库9.2或更高版本构建QPSQL插件。如果插件是用旧版本构建的,那么仅向前模式将不可用-用调用QSqlQuery::setForwardOnly()返回true,但不生效。

Warning: If you build the QPSQL plugin with PostgreSQL version 9.2 or later, then you must distribute your application with libpq version 9.2 or later. Otherwise, loading the QPSQL plugin will fail with the following message:
警告:如果您使用PostgreSQL 9.2版或更高版本构建QPSQL插件,那么您必须使用libpq 9.2版或更新版本分发应用程序。否则,加载QPSQL插件将失败,并显示以下消息:
QSqlDatabase: QPSQL driver not loaded
QSqlDatabase: available drivers: QSQLITE QMYSQL QMARIADB QODBC QPSQL
Could not create database object

While navigating the results in forward-only mode, the handle of QSqlResult may change. Applications that use the low-level handle of SQL result must get a new handle after each call to any of QSqlResult fetch functions. Example:

在仅向前模式下导航结果时,QSqlResult的句柄可能会更改。使用SQL结果的低级句柄的应用程序必须在每次调用任何QSqlResult获取函数后获得一个新句柄。例子:

QSqlQuery query;
QVariant v;
query.setForwardOnly(true);
query.exec("SELECT * FROM table");
while (query.next()) {
    // Handle changes in every iteration of the loop
    v = query.result()->handle();

    if (qstrcmp(v.typeName(), "PGresult*") == 0) {
        PGresult *handle = *static_cast<PGresult **>(v.data());
        if (handle) {
            // Do something...
        }
    }
}

While reading the results of a forward-only query with PostgreSQL, the database connection cannot be used to execute other queries. This is a limitation of libpq library. Example:

在使用PostgreSQL读取仅向前查询的结果时,数据库连接不能用于执行其他查询。这是libpq库的一个限制。例子:

int value;
QSqlQuery query1;
query1.setForwardOnly(true);
query1.exec("select * FROM table1");
while (query1.next()) {
    value = query1.value(0).toInt();
    if (value == 1) {
        QSqlQuery query2;
        query2.exec("update table2 set col=2");  // WRONG: This will discard all results of
    }                                            // query1, and cause the loop to quit
}

This problem will not occur if query1 and query2 use different database connections, or if we execute query2 after the while loop.

如果query1和query2使用不同的数据库连接,或者在while循环之后执行query2,则不会出现此问题。

Note: Some methods of QSqlDatabase like tables(), primaryIndex() implicitly execute SQL queries, so these also cannot be used while navigating the results of forward-only query.
注意:QSqlDatabase的一些方法,如tables()、primaryIndex(),隐式执行SQL查询,因此在导航仅向前查询的结果时也不能使用这些方法。
Note: QPSQL will print the following warning if it detects a loss of query results:
注意:如果QPSQL检测到查询结果丢失,它将打印以下警告:
QPSQLDriver::getResult: Query results lost - probably discarded on executing another SQL query.
How to Build the QPSQL Plugin on Unix and macOS
如何在Unix和macOS上构建QPSQL插件

You need the PostgreSQL client library and headers installed.

您需要安装PostgreSQL客户端库和头文件。

To make qt-cmake find the PostgreSQL header files and shared libraries, build the plugin the following way (assuming that the PostgreSQL client is installed in /usr/local/pgsql):

要让qt-cmake找到PostgreSQL头文件和共享库,请按照以下方式构建插件(假设PostgreSQL客户端安装在/usr/local/pgsql中):

mkdir build-psql-driver
cd build-psql-driver

qt-cmake -G Ninja <qt_installation_path>/Src/qtbase/src/plugins/sqldrivers-DCMAKE_INSTALL_PREFIX=<qt_installation_path>/<platform> -DCMAKE_INCLUDE_PATH="/usr/local/pgsql/include" -DCMAKE_LIBRARY_PATH="/usr/local/pgsql/lib"
cmake --build .
cmake --install .
How to Build the QPSQL Plugin on Windows
如何在Windows上构建QPSQL插件

Install the appropriate PostgreSQL developer libraries for your compiler. Assuming that PostgreSQL was installed in C:\pgsql, build the plugin as follows:

为编译器安装适当的PostgreSQL开发人员库。假设PostgreSQL安装在C:\pgsql中,那么按照如下方式构建插件:

mkdir build-sqldrivers
cd build-sqldrivers

qt-cmake -G Ninja <qt_installation_path>\Src\qtbase\src\plugins\sqldrivers -DCMAKE_INSTALL_PREFIX=<qt_installation_path>\<platform> -DCMAKE_INCLUDE_PATH="C:\pgsql\include" -DCMAKE_LIBRARY_PATH="C:\pgsql\lib"
cmake --build .
cmake --install .

Users of MinGW may wish to consult the following online document: PostgreSQL MinGW/Native Windows.

MinGW的用户可能希望查阅以下在线文档:PostgreSQL MinGW/Native Windows。

When you distribute your application, remember to include libpq.dll in your installation package. It must be placed in the same folder as the application executable.

分发应用程序时,请记住在安装包中包含libpq.dll。它必须与应用程序可执行文件放在同一文件夹中。

QDB2 for IBM DB2 (Version 7.1 and Above)

适用于IBM DB2的QDB2(7.1版及更高版本)

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.

Qt DB2插件使访问IBM DB2数据库成为可能。它已经在IBMDB2v7.1和7.2上进行了测试。必须安装IBMDB2开发客户端库,其中包含编译QDB2插件所需的头文件和库文件。

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

QDB2驱动程序支持准备好的查询、读取/写入Unicode字符串和读取/写入BLOB。

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

建议在调用DB2中的存储过程时使用仅向前查询(请参见QSqlQuery::setForwardOnly())。

How to Build the QDB2 Plugin on Unix and macOS
如何在Unix和macOS上构建QDB2插件
mkdir build-sqldrivers
cd build-sqldrivers

qt-cmake -G Ninja <qt_installation_path>/Src/qtbase/src/plugins/sqldrivers -DCMAKE_INSTALL_PREFIX=<qt_installation_path>/<platform> -DDB2_INCLUDE_DIR="/usr/local/db2/include" -DDB2_LIBRARY="/usr/local/db2/lib/libdb2.<so|dylib>"
cmake --build .
cmake --install .
How to Build the QDB2 Plugin on Windows
如何在Windows上构建QDB2插件

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

DB2头文件和包含文件应该已经安装在正确的目录中。您只需要按照如下方式构建插件:

mkdir build-sqldrivers
cd build-sqldrivers

qt-cmake -G Ninja <qt_installation_path>\Src\qtbase\src\plugins\sqldrivers -DCMAKE_INSTALL_PREFIX=<qt_installation_path>\<platform> -DDB2_INCLUDE_DIR="C:\db2\include" -DDB2_LIBRARY="C:\db2\lib\db2.lib"
cmake --build .
cmake --install .

QSQLITE for SQLite (Version 3 and Above)

用于SQLite的QSQLITE(版本3及以上)

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 and temporary databases. Simply pass respectively ":memory:" or an empty string as the database name.

Qt SQLite插件使访问SQLite数据库成为可能。SQLite是一个进程内数据库,这意味着不需要数据库服务器。SQLite对单个文件进行操作,打开连接时必须将该文件设置为数据库名称。如果文件不存在,SQLite将尝试创建它。SQLite还支持内存和临时数据库。只需分别传递“:memory:”或一个空字符串作为数据库名称。

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对多个用户和多个事务有一些限制。如果试图从不同的事务中读取/写入资源,那么应用程序可能会冻结,直到一个事务提交或回滚。Qt SQLite驱动程序将重试写入锁定的资源,直到超时为止(请参阅QSqlDatabase::setConnectOptions()中的QSQLITE_BUSY_TIMEOUT)。

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.

在SQLite中,除INTEGER PRIMARY KEY列外,任何列都可以用于存储任何类型的值。例如,声明为INTEGER的列可能在一行中包含一个整数值,而在下一行中则包含一个文本值。这是由于SQLite将值的类型与值本身相关联,而不是与存储该值的列相关联。其结果是,QSqlField::type()返回的类型仅指示字段的推荐类型。不应由此对实际类型进行假设,并且应检查单个值的类型。

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

在执行选择时,驱动程序被锁定以进行更新。这可能会在使用QSqlTableModel时造成问题,因为Qt的项视图会根据需要获取数据(在QSqlTableModel的情况下使用QSqlQuery::fetchMore())。

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

可以在上找到有关SQLite的信息http://www.sqlite.org.

How to Build the QSQLITE Plugin
如何构建QSQLITE插件

SQLite version 3 is included as a third-party library within Qt. It can be built by passing the -DFEATURE_system_sqlite=OFF parameter to the qt-cmake command line.

SQLite版本3作为第三方库包含在Qt中。它可以通过将-DFEATURE_system_sqlite=OFF参数传递到qt-cmake命令行来构建。

If you do not want to use the SQLite library included with Qt, you can pass -DFEATURE_system_sqlite=ON to the qt-cmake command line to use the SQLite libraries of the operating system. This is recommended whenever possible, as it reduces the installation size and removes one component for which you need to track security advisories.

如果不想使用Qt中包含的SQLite库,可以将-DFEATURE_system_SQLite=ON传递到qt-cmake命令行,以使用操作系统的SQLite库。建议尽可能这样做,因为这样可以减少安装规模,并删除一个需要跟踪安全建议的组件。

On Unix and macOS (replace $SQLITE with the directory where SQLite resides):

在Unix和macOS上(将$SQLITE替换为SQLITE所在的目录):

mkdir build-sqldrivers
cd build-sqldrivers

qt-cmake -G Ninja <qt_installation_path>/Src/qtbase/src/plugins/sqldrivers -DCMAKE_INSTALL_PREFIX=<qt_installation_path>/<platform> -DFEATURE_system_sqlite=ON -DCMAKE_INCLUDE_PATH="$SQLITE/include" -DCMAKE_LIBRARY_PATH="$SQLITE/lib"
cmake --build .
cmake --install .

On Windows (assuming that SQLite is installed in C:\SQLITE):

在Windows上(假设SQLite安装在C:\SQLite中):

mkdir build-sqldrivers
cd build-sqldrivers

qt-cmake -G Ninja <qt_installation_path>\Src\qtbase\src\plugins\sqldrivers -DCMAKE_INSTALL_PREFIX=<qt_installation_path>\<platform> -DFEATURE_system_sqlite=ON -DCMAKE_INCLUDE_PATH="C:\SQLITE\include" -DCMAKE_LIBRARY_PATH="C:\SQLITE\lib"
cmake --build .
cmake --install .
Enable REGEXP operator

启用REGEXP操作员

SQLite comes with a REGEXP operation. However the needed implementation must be provided by the user. For convenience a default implementation can be enabled by setting the connect option QSQLITE_ENABLE_REGEXP before the database connection is opened. Then a SQL statement like "column REGEXP 'pattern'" basically expands to the Qt code

SQLite附带REGEXP操作。然而,所需的实现必须由用户提供。为了方便起见,可以通过在打开数据库连接之前设置连接选项QSQLITE_ENABLE_REGEXP来启用默认实现。然后,类似于“列REGEXP‘模式’”的SQL语句基本上扩展到Qt代码

column.contains(QRegularExpression("pattern"));

For better performance the regular expressions are cached internally. By default the cache size is 25, but it can be changed through the option's value. For example passing "QSQLITE_ENABLE_REGEXP=10" reduces the cache size to 10.

为了获得更好的性能,正则表达式在内部缓存。默认情况下,缓存大小为25,但可以通过选项的值进行更改。例如,传递“QSQLITE_ENABLE_REGEXP=10”会将缓存大小减小到10。

QSQLITE File Format Compatibility
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.

SQLite次要版本有时会破坏文件格式的前向兼容性。例如,SQLite 3.3可以读取用SQLite 3.2创建的数据库文件,但用SQLite 3.3创建的数据库不能被SQLite 3.2读取。有关版本之间文件格式兼容性的信息,请参阅SQLite文档和更改日志。

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.

Qt次要版本通常遵循SQLite次要版本,而Qt补丁版本遵循SQLite补丁版本。因此,修补程序版本既向后兼容,又向前兼容。

To force SQLite to use a specific file format, it is necessary 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.

要强制SQLite使用特定的文件格式,有必要使用您自己的SQLite库构建和发布您自己的数据库插件,如上图所示。通过在构建SQLite时设置SQLITE_DEFAULT_FILE_FORMAT定义,可以强制某些版本的SQLite编写特定的文件格式。

QIBASE for Borland InterBase

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. Firebird must be used with a server configuration.

Qt InterBase插件使访问InterBase和Firebird数据库成为可能。InterBase既可以用作客户端/服务器,也可以不用作服务器,在这种情况下,它可以对本地文件进行操作。数据库文件必须存在,然后才能建立连接。Firebird必须与服务器配置一起使用。

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.

请注意,InterBase要求指定数据库文件的完整路径,无论该文件是存储在本地还是其他服务器上。

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

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

您需要InterBase/Firebird开发头文件和库来构建这个插件。

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.

由于许可证与GPL不兼容,Qt开源版的用户不允许将此插件链接到InterBase的商业版。请使用Firebird或免费版的InterBase。

QIBASE Unicode Support and Text Encoding
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.

默认情况下,驱动程序使用UNICODE_FSS连接到数据库。这可以通过在打开连接之前使用QSqlDatabase::setConnectOptions()设置ISC_DPB_LC_CTYPE参数来覆盖。

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

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

如果Qt不支持给定的文本编码,则驱动程序将发出警告消息,并使用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 Stored procedures
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:

InterBase/Firebird返回OUT值作为结果集,因此在调用存储过程时,只需要通过QSqlQuery::bindValue()绑定IN值。RETURN/OUT值可以通过QSqlQuery::value()检索。例子:

QSqlQuery q;
q.exec("execute procedure my_procedure");
if (q.next())
    qDebug() << q.value(0); // outputs the first RETURN/OUT value
How to Build the QIBASE Plugin on Unix and macOS
如何在Unix和macOS上构建QIBASE插件

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

以下假设InterBase或Firebird安装在/opt/InterBase中:

If you are using InterBase:

如果您正在使用InterBase:

mkdir build-sqldrivers
cd build-sqldrivers

qt-cmake -G Ninja <qt_installation_path>/Src/qtbase/src/plugins/sqldrivers -DCMAKE_INSTALL_PREFIX=<qt_installation_path>/<platform> -DInterbase_INCLUDE_DIR="/opt/interbase/include" -DInterbase_LIBRARY="/opt/interbase/lib/libgds.<so|dylib>"
cmake --build .
cmake --install .

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

如果您正在使用Firebird,则必须明确设置Firebird库:

mkdir build-sqldrivers
cd build-sqldrivers

qt-cmake -G Ninja <qt_installation_path>/Src/qtbase/src/plugins/sqldrivers -DCMAKE_INSTALL_PREFIX=<qt_installation_path>/<platform> -DInterbase_INCLUDE_DIR="/opt/interbase/include" -DInterbase_LIBRARY="/opt/interbase/lib/libfbclient.<so|dylib>"
cmake --build .
cmake --install .
How to Build the QIBASE Plugin on Windows
如何在Windows上构建QIBASE插件

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

以下假设InterBase或Firebird安装在C:\InterBase中:

If you are using InterBase:

如果您正在使用InterBase:

mkdir build-sqldrivers
cd build-sqldrivers

qt-cmake -G Ninja <qt_installation_path>\Src\qtbase\src\plugins\sqldrivers -DCMAKE_INSTALL_PREFIX=<qt_installation_path>\<platform> -DInterbase_INCLUDE_DIR="C:\interbase\include" -DInterbase_LIBRARY="C:\interbase\gds.lib"
cmake --build .
cmake --install .

If you are using Firebird:

如果您正在使用Firebird:

mkdir build-sqldrivers
cd build-sqldrivers

qt-cmake -G Ninja <qt_installation_path>\Src\qtbase\src\plugins\sqldrivers -DCMAKE_INSTALL_PREFIX=<qt_installation_path>\<platform> -DInterbase_INCLUDE_DIR="C:\interbase\include" -DInterbase_LIBRARY="C:\interbase\lib\fbclient_ms.lib"
cmake --build .
cmake --install .

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

请注意,C:\interbase\bin必须位于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 distribution 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++.

应该始终使用已使用在项目中使用的编译器相同的编译器编译的客户端库。如果无法获得源发行版来自己编译客户端库,则必须确保预编译的库与编译器兼容,否则会出现许多“未定义符号”错误。一些编译器有转换库的工具,例如Borland提供了COF2OMF.EXE工具来转换使用Microsoft Visual C++生成的库。

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

如果插件编译成功但无法加载,请确保满足以下要求:

  • Ensure that the plugin is in the correct directory. You can use QApplication::libraryPaths() to determine where Qt looks for plugins.

  • 请确保插件位于正确的目录中。可以使用QApplication::libraryPaths()来确定Qt在哪里查找插件。

  • Ensure that the client libraries of the DBMS are available on the system. On Unix, run the command ldd and pass the name of the plugin as parameter, for example ldd libqsqlmysql.so. You will get a warning if any of the client libraries could not be found. On Windows, you can use Visual Studio's dependency walker. With Qt Creator, you can update the PATH environment variable in the Run section of the Project panel to include the path to the folder containing the client libraries.

  • 确保DBMS的客户端库在系统上可用。在Unix上,运行命令ldd并将插件的名称作为参数传递,例如ldd libqsqlmysql.so。如果找不到任何客户端库,将收到警告。在Windows上,您可以使用Visual Studio的依赖查询器。使用Qt Creator,您可以在“项目”面板的“运行”部分更新PATH环境变量,以包括包含客户端库的文件夹的路径。

  • Compile Qt with QT_DEBUG_COMPONENT defined to get very verbose debug output when loading plugins.

  • 使用定义的QT_DEBUG_COMPONENT编译Qt,以便在加载插件时获得非常详细的调试输出。

Make sure you have followed the guide to Deploying Plugins.

请确保已经遵循了部署插件的指南。

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.

QSqlDatabase负责加载和管理数据库驱动程序插件。添加数据库时(请参见QSqlDatabase::addDatabase()),将加载相应的驱动程序插件(使用QSqlDriverPlugin)。QSqlDatabase依赖于驱动程序插件为QSqlDriver和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.

QSqlDriver是一个抽象基类,它定义了SQL数据库驱动程序的功能。这包括QSqlDriver::open()和QSqlDriver::close()等函数。QSqlDriver负责连接到数据库,建立适当的环境等。此外,QSqlDriver可以创建适合特定数据库API的QSqlQuery对象。QSqlDatabase将其许多函数调用直接转发给QSqlDriver,后者提供了具体的实现。

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.

QSqlResult是一个抽象基类,它定义了SQL数据库查询的功能。这包括SELECT、UPDATE和ALTER TABLE等语句。QSqlResult包含QSqlResult::next()和QSqlResult::value()等函数。QSqlResult负责向数据库发送查询、返回结果数据等。QSqlQuery将其许多函数调用直接转发给提供具体实现的QSqlResult。

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.

QSqlDriver和QSqlResult是紧密相连的。当实现QtSQL驱动程序时,这两个类都必须是子类,并且必须实现每个类中的抽象虚拟方法。

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_PLUGIN_METADATA() 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/qtbase/src/plugins/sqldrivers.

要将Qt SQL驱动程序实现为插件(以便在运行时被Qt库识别和加载),该驱动程序必须使用Q_PLUGIN_METADATA()宏。阅读如何创建Qt插件了解更多信息。还可以在QTDIR/qtbase/src/plugins/sqldrivers中查看Qt附带的SQL插件是如何做到这一点的。

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

以下代码可以用作SQL驱动程序的框架:

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

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

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

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

© 2023 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值