Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
sql-driver.qdoc
Go to the documentation of this file.
1
// Copyright (C) 2020 The Qt Company Ltd.
2
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only
3
4
/*!
5
\page sql-driver.html
6
\title SQL Database Drivers
7
\brief How to configure and install Qt SQL drivers for supported databases.
8
9
The Qt SQL module uses driver \l{How to Create Qt
10
Plugins}{plugins} to communicate with the different database
11
APIs. Since Qt's SQL Module API is database-independent, all
12
database-specific code is contained within these drivers. Several
13
drivers are supplied with Qt, and other drivers can be added. The
14
driver source code is supplied and can be used as a model for
15
\l{#development}{writing your own drivers}.
16
17
\section1 Supported Databases
18
19
The table below lists the drivers included with Qt:
20
21
\table
22
\header \li Driver name \li DBMS
23
\row \li \l{#QDB2}{QDB2} \li IBM DB2 (version 7.1 and above)
24
\row \li \l{#QIBASE}{QIBASE} \li Borland InterBase / Firebird
25
\row \li \l{#QMYSQL}{QMYSQL / MARIADB} \li MySQL or MariaDB (version 5.6 and above)
26
\row \li \l{#QOCI}{QOCI} \li Oracle Call Interface Driver (version 12.1 and above)
27
\row \li \l{#QODBC}{QODBC}
28
\li Open Database Connectivity (ODBC) - Microsoft SQL Server and other
29
ODBC-compliant databases
30
\row \li \l{#QPSQL}{QPSQL} \li PostgreSQL (versions 7.3 and above)
31
\row \li \l{#QSQLITE}{QSQLITE} \li SQLite version 3
32
\row \li \l{#QMIMER}{QMIMER} \li Mimer SQL (version 11 and above)
33
\endtable
34
35
SQLite is the in-process database system with the best test coverage
36
and support on all platforms. Oracle via OCI, PostgreSQL, and MySQL
37
through either ODBC or a native driver are well-tested on Windows and
38
Linux. The completeness of the support for other systems depends on the
39
availability and quality of client libraries.
40
41
\note To build a driver plugin you need to have the appropriate
42
client library for your Database Management System (DBMS). This provides
43
access to the API exposed by the DBMS, and is typically shipped with it.
44
Most installation programs also allow you to install "development
45
libraries", and these are what you need. These libraries are responsible
46
for the low-level communication with the DBMS. Also make sure to install
47
the correct database libraries for your Qt architecture (32 or 64 bit).
48
49
\note When using Qt under Open Source terms but with a proprietary
50
database, verify the client library's license compatibility with
51
the LGPL.
52
53
\target building
54
\section1 Building the Drivers
55
\target DriverWithQt
56
\section2 Compile Qt with a specific driver
57
58
The Qt \c configure script tries to
59
automatically detect the available client libraries on your
60
machine. Run \c{configure -help} to see what drivers can be
61
built. You should get an output similar to this:
62
63
\snippet code/doc_src_sql-driver.qdoc 0
64
65
The \c configure script cannot detect the necessary libraries
66
and include files if they are not in the standard paths, so it
67
may be necessary to specify these paths using either
68
driver-specific include and library path variables or \c CMAKE_INCLUDE_PATH
69
and \c CMAKE_LIBRARY_PATH. For example, if your MySQL files are
70
installed in \c{C:\mysql-connector-c-6.1.11-winx64} on Windows, then pass
71
the following parameter to double-dash part of configure line:
72
\snippet code/doc_src_sql-driver.qdoc 42
73
When you configure drivers in the manner described above, CMake skips any
74
dependency checks and uses the provided paths as is. This is especially
75
useful if the package provides its own set of system libraries that
76
should not be recognized by the build routine.
77
78
The particulars for each driver are explained below.
79
80
\note If something goes wrong and you want CMake to recheck your
81
available drivers, you might need to remove \e{CMakeCache.txt} from the build
82
directory.
83
84
\target DriverStandalone
85
\section2 Compile only a specific SQL driver
86
87
It's possible to only compile a specific SQL driver when Qt is already built
88
or installed as binary version. But you have to make sure to install
89
the exact same version of the Qt sources (for example through the \QMT) -
90
otherwise you might get compile errors due to changed apis.
91
Also make sure to properly set up the build environment by executing the
92
appropriate Qt command prompt in the Windows Start menu.
93
94
A typical \c qt-cmake run (in this case to configure for MySQL) looks like this:
95
96
\snippet code/doc_src_sql-driver.qdoc 41
97
98
After configuring with \c qt-cmake, build the driver by running \c ninja.
99
100
\note As mentioned in \l{#DriverWithQt}{Compile Qt with a specific driver},
101
if the driver could not be found or is not enabled, start over by removing
102
\e{CMakeCache.txt}.
103
104
Due to the practicalities of dealing with external dependencies,
105
only the SQLite plugin is shipped with binary builds of Qt.
106
Binary builds of Qt for Windows also include the ODBC and PostgreSQL plugin.
107
To be able to add additional drivers to the Qt installation
108
without re-building all of Qt, it is possible to configure
109
and build the \c qtbase/src/plugins/sqldrivers directory outside
110
of a full Qt build directory. Note that it is not possible to
111
\e configure each driver separately, only all of them at once.
112
Drivers can be \e built separately, though.
113
114
\note You need to specify \c{CMAKE_INSTALL_PREFIX}, if you want to install
115
plugins after the build is finished.
116
117
\section1 Driver Specifics
118
119
\target QMYSQL
120
\section2 QMYSQL for MySQL or MariaDB 5.6 and higher
121
122
MariaDB is a fork of MySQL intended to remain free and open-source software
123
under the GNU General Public License. MariaDB intended to maintain high
124
compatibility with MySQL, ensuring a drop-in replacement capability with
125
library binary parity and exact matching with MySQL APIs and commands.
126
Therefore the plugin for MySQL and MariaDB are combined into one Qt plugin.
127
128
\section3 Timestamp Support
129
Since Qt 6.8, QDateTime values are converted to UTC before insertion and
130
back from UTC during retrieval. To make this work, the driver sets
131
the connection time zone to UTC during open() (SET time_zone = '+00:00').
132
Since MySQL does not store any timezone information, this information is
133
lost and all retrieved QDateTime values are UTC.
134
135
\section3 QMYSQL Stored Procedure Support
136
137
MySQL has stored procedure support at the SQL level, but no
138
API to control IN, OUT, and INOUT parameters. Therefore, parameters
139
have to be set and read using SQL commands instead of QSqlQuery::bindValue().
140
141
Example stored procedure:
142
143
\snippet code/doc_src_sql-driver.qdoc 1
144
145
Source code to access the OUT values:
146
147
\snippet code/doc_src_sql-driver.cpp 2
148
149
\note \c{@outval1} and \c{@outval2} are variables local to the current
150
connection and will not be affected by queries sent from another host
151
or connection.
152
153
\section3 Embedded MySQL Server
154
155
The MySQL embedded server is a drop-in replacement for the normal
156
client library. With the embedded MySQL server, a MySQL server is
157
not required to use MySQL functionality.
158
159
To use the embedded MySQL server, simply link the Qt plugin to \c
160
libmysqld instead of \c libmysqlclient. This can be done by adding
161
\c{-DMySQL_LIBRARY=<path/to/mysqld/>libmysqld.<so|lib|dylib>} to the configure command line.
162
163
Please refer to the MySQL documentation, chapter "libmysqld, the Embedded
164
MySQL Server Library" for more information about the MySQL embedded server.
165
166
\section3 Connection options
167
The Qt MySQL/MariaDB plugin honors the following connection options:
168
\table
169
\header \li Attribute \li Possible value
170
\row
171
\li CLIENT_COMPRESS
172
\li If set, switches to compressed protocol after successful authentication
173
\row
174
\li CLIENT_FOUND_ROWS
175
\li If set, send found rows instead of affected rows
176
\row
177
\li CLIENT_IGNORE_SPACE
178
\li If set, ignore spaces before '('
179
\row
180
\li CLIENT_NO_SCHEMA
181
\li If set, don't allow database.table.column
182
\row
183
\li CLIENT_INTERACTIVE
184
\li If set, client is treated as interactive
185
\row
186
\li MYSQL_OPT_PROTOCOL
187
\li explicitly specify the protocol to use:\br
188
MYSQL_PROTOCOL_TCP: use tcp connection (ip/hostname specified through setHostname())
189
MYSQL_PROTOCOL_SOCKET: connect through a socket specified in UNIX_SOCKET
190
MYSQL_PROTOCOL_PIPE: connect through a named pipe specified in UNIX_SOCKET
191
MYSQL_PROTOCOL_MEMORY: connect through shared memory specified in MYSQL_SHARED_MEMORY_BASE_NAME
192
\row
193
\li UNIX_SOCKET
194
\li Specifies the socket or named pipe to use, even it's called UNIX_SOCKET it
195
can also be used on windows
196
\row
197
\li MYSQL_SHARED_MEMORY_BASE_NAME
198
\li Specified the shared memory segment name to use
199
\row
200
\li MYSQL_OPT_RECONNECT
201
\li TRUE or 1: Automatically reconnect after connection loss\br
202
FALSE or 0: No automatic reconnect after connection loss (default)\br
203
See \l {https://dev.mysql.com/doc/c-api/8.0/en/c-api-auto-reconnect.html}
204
{Automatic Reconnection Control}
205
\row
206
\li MYSQL_OPT_CONNECT_TIMEOUT
207
\li The connect timeout in seconds
208
\row
209
\li MYSQL_OPT_READ_TIMEOUT
210
\li The timeout in seconds for each attempt to read from the server
211
\row
212
\li MYSQL_OPT_WRITE_TIMEOUT
213
\li The timeout in seconds for each attempt to write to the server
214
\row
215
\li MYSQL_OPT_LOCAL_INFILE
216
\li Set to 1 to enable the support for local
217
\l {https://dev.mysql.com/doc/refman/8.0/en/load-data.html} {LOAD_DATA},
218
disabled if not set or 0
219
\row
220
\li MYSQL_OPT_SSL_MODE
221
\li The security state to use for the connection to the server: SSL_MODE_DISABLED,
222
SSL_MODE_PREFERRED, SSL_MODE_REQUIRED, SSL_MODE_VERIFY_CA, SSL_MODE_VERIFY_IDENTITY.
223
Only available when linked against MySQL 5.7.10 or higher.
224
\row
225
\li MYSQL_OPT_TLS_VERSION
226
\li A list of protocols the client permits for encrypted connections. The value can be
227
a combination of 'TLSv1' ,' TLSv1.1', 'TLSv1.2' or 'TLSv1.3' depending on the used \l
228
{https://dev.mysql.com/doc/refman/8.0/en/encrypted-connection-protocols-ciphers.html#encrypted-connection-protocol-configuration}
229
{MySQL server} version.
230
Only available when linked against MySQL 5.7.11 or higher or MariaDB C Connector 3.1.10.
231
\row
232
\li MYSQL_OPT_SSL_KEY / SSL_KEY (deprecated)
233
\li The path name of the client private key file
234
\row
235
\li MYSQL_OPT_SSL_CERT / SSL_CERT (deprecated)
236
\li The path name of the client public key certificate file
237
\row
238
\li MYSQL_OPT_SSL_CA / SSL_CA (deprecated)
239
\li The path name of the Certificate Authority (CA) certificate file
240
\row
241
\li MYSQL_OPT_SSL_CAPATH / SSL_CAPATH (deprecated)
242
\li The path name of the directory that contains trusted SSL CA certificate files
243
\row
244
\li MYSQL_OPT_SSL_CIPHER / SSL_CIPHER (deprecated)
245
\li The list of permissible ciphers for SSL encryption
246
\row
247
\li MYSQL_OPT_SSL_CRL
248
\li The path name of the file containing certificate revocation lists
249
\row
250
\li MYSQL_OPT_SSL_CRLPATH
251
\li The path name of the directory that contains files containing certificate revocation lists
252
\row
253
\li MYSQL_OPT_SSL_VERIFY_SERVER_CERT
254
\li TRUE or 1: Enable verification of the server's Common Name identity (default)\br
255
FALSE or 0: Enable verification of the server's Common Name identity\br
256
Only available when linked against MySQL 5.7.11 or MariaDB, removed with MySQL 8.0.
257
\endtable
258
For more detailed information about the connect options please refer
259
to the \l {https://dev.mysql.com/doc/c-api/8.0/en/mysql-options.html}
260
{mysql_options()} MySQL documentation.
261
262
263
\section3 How to Build the QMYSQL Plugin on Unix and \macos
264
265
You need the MySQL / MariaDB header files, as well as the shared library
266
\c{libmysqlclient.<so|dylib>} / \c{libmariadb.<so|dylib>}. Depending on your Linux distribution,
267
you may need to install a package which is usually called "mysql-devel"
268
or "mariadb-devel".
269
270
Tell \c qt-cmake where to find the MySQL / MariaDB header files and shared
271
libraries (here it is assumed that MySQL / MariaDB is installed in
272
\c{/usr/local}) and build:
273
274
\snippet code/doc_src_sql-driver.qdoc 3
275
276
\section3 How to Build the QMYSQL Plugin on Windows
277
278
You need to get the MySQL installation files (e.g.
279
\l {https://dev.mysql.com/downloads/installer/}{MySQL web installer} or
280
\l {https://downloads.mariadb.com/Connectors/c/}{MariaDB C Connector}).
281
Run the installer,
282
select custom installation and install the MySQL C Connector
283
which matches your Qt installation (x86 or x64).
284
After installation check that the needed files are there:
285
\list
286
\li \c {<MySQL dir>/lib/libmysql.lib}
287
\li \c {<MySQL dir>/lib/libmysql.dll}
288
\li \c {<MySQL dir>/include/mysql.h}
289
\endlist
290
and for MariaDB
291
\list
292
\li \c {<MariaDB dir>/lib/libmariadb.lib}
293
\li \c {<MariaDB dir>/lib/libmariadb.dll}
294
\li \c {<MariaDB dir>/include/mysql.h}
295
\endlist
296
297
\note As of MySQL 8.0.19, the C Connector is no longer offered as a standalone
298
installable component. Instead, you can get \c{mysql.h} and \c{libmysql.*} by
299
installing the full MySQL Server (x64 only) or the
300
\l{https://downloads.mariadb.org/connector-c/}{MariaDB C Connector}.
301
302
Build the plugin as follows (here it is assumed that \c{<MySQL dir>} is
303
\c{C:\mysql-8.0.22-winx64}):
304
305
\snippet code/doc_src_sql-driver.qdoc 5
306
307
When you distribute your application, remember to include \e libmysql.dll / \e libmariadb.dll
308
in your installation package. It must be placed in the same folder
309
as the application executable. \e libmysql.dll additionally needs the
310
MSVC runtime libraries which can be installed with
311
\l {https://support.microsoft.com/en-us/help/2977003/the-latest-supported-visual-c-downloads}{vcredist.exe}
312
313
\target QOCI
314
\section2 QOCI for the Oracle Call Interface (OCI)
315
316
The Qt OCI plugin supports connecting to Oracle database as determined by
317
the version of the instant client used. This is dependent on what Oracle
318
indicates it supports. The plugin will auto-detect the database version
319
and enable features accordingly.
320
321
It's possible to connect to a Oracle database without a tnsnames.ora file.
322
This requires that the database SID is passed to the driver as the database
323
name, and that a hostname is given.
324
325
\section3 OCI User Authentication
326
327
The Qt OCI plugin supports authentication using
328
external credentials (OCI_CRED_EXT). Usually, this means that the database
329
server will use the user authentication provided by the operating system
330
instead of its own authentication mechanism.
331
332
Leave the username and password empty when opening a connection with
333
QSqlDatabase to use the external credentials authentication.
334
335
\section3 OCI BLOB/LOB Support
336
337
Binary Large Objects (BLOBs) can be read and written, but be aware
338
that this process may require a lot of memory. You should use a forward
339
only query to select LOB fields (see QSqlQuery::setForwardOnly()).
340
341
Inserting BLOBs should be done using either a prepared query where the
342
BLOBs are bound to placeholders or QSqlTableModel, which uses a prepared
343
query to do this internally.
344
345
\section3 Connection options
346
The Qt OCI plugin honors the following connection options:
347
\table
348
\header \li Attribute \li Possible value
349
\row
350
\li OCI_ATTR_PREFETCH_ROWS
351
\li Sets the OCI attribute
352
\l {https://docs.oracle.com/database/121/LNOCI/oci04sql.htm#LNOCI16355}
353
{OCI_ATTR_PREFETCH_ROWS} to the specified value
354
\row
355
\li OCI_ATTR_PREFETCH_MEMORY
356
\li Sets the OCI attribute
357
\l {https://docs.oracle.com/database/121/LNOCI/oci04sql.htm#LNOCI16355}
358
{OCI_ATTR_PREFETCH_MEMORY} to the specified value
359
\row
360
\li OCI_AUTH_MODE
361
\li OCI_SYSDBA: authenticate for SYSDBA access\br
362
OCI_SYSOPER: authenticate for SYSOPER access\br
363
OCI_DEFAULT: authenticate with normal access\br
364
see \l {https://docs.oracle.com/cd/B10500_01/appdev.920/a96584/oci15r13.htm}
365
{OCISessionBegin} for more information about the access modes
366
\endtable
367
368
\section3 How to Build the OCI Plugin on Unix and \macos
369
370
All you need is the " - Basic" and "Instant Client
371
Package - SDK".
372
373
Oracle library files required to build the driver:
374
375
\list
376
\li \c libclntsh.<so|dylib> (all versions)
377
\endlist
378
379
Tell \c qt-cmake where to find the Oracle header files and shared
380
libraries and build.
381
382
We assume that you installed the RPM packages of the Instant Client Package SDK
383
(you need to adjust the version number accordingly):
384
\snippet code/doc_src_sql-driver.qdoc 7
385
386
\note If you are using the Oracle Instant Client package,
387
you will need to set LD_LIBRARY_PATH when building the OCI SQL plugin,
388
and when running an application that uses the OCI SQL plugin.
389
390
\section3 How to Build the OCI Plugin on Windows
391
392
Choosing the option "Programmer" in the Oracle Client Installer from
393
the Oracle Client Installation CD is generally sufficient to build the
394
plugin. For some versions of Oracle Client, you may also need to select
395
the "Call Interface (OCI)" option if it is available.
396
397
Build the plugin as follows (here it is assumed that Oracle Client is
398
installed in \c{C:\oracle} and SDK is installed in \c{C:\oracle\sdk}):
399
400
\snippet code/doc_src_sql-driver.qdoc 8
401
402
When you run your application, you will also need to add the \c oci.dll
403
path to your \c PATH environment variable:
404
405
\snippet code/doc_src_sql-driver.qdoc 9
406
407
\target QODBC
408
\section2 QODBC for Open Database Connectivity (ODBC)
409
410
ODBC is a general interface that allows you to connect to multiple
411
DBMSs using a common interface. The QODBC driver allows you to connect
412
to an ODBC driver manager and access the available data sources. Note
413
that you also need to install and configure ODBC drivers for the ODBC
414
driver manager that is installed on your system. The QODBC plugin
415
then allows you to use these data sources in your Qt applications.
416
417
\note You should use the native driver, if it is available, instead
418
of the ODBC driver. ODBC support can be used as a fallback for compliant
419
databases if no native driver is available.
420
421
On Windows, an ODBC driver manager is installed by default.
422
For Unix systems, there are some implementations which must be
423
installed first. Note that every end user of your application is
424
required to have an ODBC driver manager installed, otherwise the
425
QODBC plugin will not work.
426
427
When connecting to an ODBC datasource, you should pass the name
428
of the ODBC datasource (DSN) to the QSqlDatabase::setDatabaseName()
429
function, rather than the actual database name.
430
It's also possible to pass a FILEDSN (*.dsn) filename or a complete
431
ODBC driver string. When passing a driver string you must make sure,
432
that all parameters (username, password, ...) are properly escaped.
433
Passing the username or password through the QSqlDatabase functions,
434
the escaping is done by the QODBC plugin.
435
436
The QODBC Plugin needs an ODBC compliant driver manager version 2.0 or
437
later. Some ODBC drivers claim to be version-2.0-compliant,
438
but do not offer all the necessary functionality. The QODBC plugin
439
therefore checks whether the data source can be used after a
440
connection has been established, and refuses to work if the check
441
fails. If you do not like this behavior, you can remove the \c{#define
442
ODBC_CHECK_DRIVER} line from the file \c{qsql_odbc.cpp}. Do this at
443
your own risk!
444
445
By default, Qt instructs the ODBC driver to behave as an ODBC 2.x
446
driver. However, for some \e{driver-manager/ODBC 3.x-driver}
447
combinations (e.g., \e{unixODBC/MaxDB ODBC}), telling the ODBC
448
driver to behave as a 2.x driver can cause the driver plugin to
449
have unexpected behavior. To avoid this problem, instruct the ODBC
450
driver to behave as a 3.x driver by
451
\l{QSqlDatabase::setConnectOptions()} {setting the connect option}
452
\c{"SQL_ATTR_ODBC_VERSION=SQL_OV_ODBC3"} before you
453
\l{QSqlDatabase::open()} {open your database connection}. Note
454
that this will affect multiple aspects of ODBC driver behavior,
455
e.g., the SQLSTATEs. Before setting this connect option, consult
456
your ODBC documentation about behavior differences you can expect.
457
458
If you experience very slow access of the ODBC datasource, make sure
459
that ODBC call tracing is turned off in the ODBC datasource manager.
460
461
Some drivers do not support scrollable cursors. In that case, only
462
queries in \l QSqlQuery::setForwardOnly() mode can be used successfully.
463
464
\section3 Timestamp Support
465
ODBC is using TIMESTAMP_STRUCT which has no information about any
466
timezone or similar. Due to this, the QDateTime is used without honoring
467
the timezone at all.
468
\note: This might change in the future.
469
470
\section3 ODBC Stored Procedure Support
471
472
With Microsoft SQL Server the result set returned by a stored
473
procedure that uses the return statement, or returns multiple result
474
sets, will be accessible only if you set the query's forward only
475
mode to \e forward using \l QSqlQuery::setForwardOnly().
476
477
\snippet code/doc_src_sql-driver.cpp 10
478
479
\note The value returned by the stored procedure's return statement
480
is discarded.
481
482
\section3 ODBC Unicode Support
483
484
The QODBC Plugin will use the Unicode API if UNICODE is defined. On
485
Windows based systems, this is the default. Note that the ODBC
486
driver and the DBMS must also support Unicode.
487
488
For the Oracle 9 ODBC driver (Windows), it is necessary to check
489
"SQL_WCHAR support" in the ODBC driver manager otherwise Oracle
490
will convert all Unicode strings to local 8-bit representation.
491
492
\section3 Connection options
493
The Qt ODBC plugin honors the following connection options:
494
\table
495
\header \li Attribute \li Possible value
496
\row
497
\li SQL_ATTR_ACCESS_MODE
498
\li SQL_MODE_READ_ONLY: open the database in read-only mode\br
499
SQL_MODE_READ_WRITE: open the database in read-write mode (default)
500
\row
501
\li SQL_ATTR_LOGIN_TIMEOUT
502
\li Number of seconds to wait for the database connection
503
during login (a value of 0 will wait forever)
504
\row
505
\li SQL_ATTR_CONNECTION_TIMEOUT
506
\li Number of seconds to wait for any request to the database
507
(a value of 0 will wait forever)
508
\row
509
\li SQL_ATTR_CURRENT_CATALOG
510
\li The catalog (database) to use for this connection
511
\row
512
\li SQL_ATTR_METADATA_ID
513
\li SQL_TRUE: the string argument of catalog functions are treated
514
as identifiers\br
515
SQL_FALSE: the string arguments of catalog functions are not
516
treated as identifiers
517
\row
518
\li SQL_ATTR_PACKET_SIZE
519
\li Specifies the network packet size in bytes
520
\row
521
\li SQL_ATTR_TRACEFILE
522
\li A string containing the name of the trace file
523
\row
524
\li SQL_ATTR_TRACE
525
\li SQL_OPT_TRACE_ON: Enable database query tracing\br
526
SQL_OPT_TRACE_OFF: Disable database query tracing (default)
527
\row
528
\li SQL_ATTR_CONNECTION_POOLING
529
\li Enable or disable connection pooling at the environment level.\br
530
SQL_CP_DEFAULT, SQL_CP_OFF: Connection pooling is turned off (default)\br
531
SQL_CP_ONE_PER_DRIVER: A single connection pool is supported for each driver\br
532
SQL_CP_ONE_PER_HENV: A single connection pool is supported for each environment
533
\row
534
\li SQL_ATTR_ODBC_VERSION
535
\li SQL_OV_ODBC3: The driver should act as a ODBC 3.x driver\br
536
SQL_OV_ODBC2: The driver should act as a ODBC 2.x driver (default)
537
\row
538
\li SQL_ATTR_CP_MATCH
539
\li Can be either SQL_CP_STRICT_MATCH, SQL_CP_RELAXED_MATCH or
540
SQL_CP_MATCH_DEFAULT. See \l {https://learn.microsoft.com/en-us/sql/odbc/reference/syntax/sqlconnect-function}
541
{SQLConnect()} ODBC documentation for more information
542
\row
543
\li SQL_PERCENT_ENCODE_PASSWORD
544
\li This is a custom Qt ODBC driver option to support drivers (Oracle, PostgreSQL) which need special
545
characters encoded with percent encoding instead in curly braces like ODBC standard defines.
546
547
\endtable
548
For more detailed information about the connect options please refer
549
to the \l {https://learn.microsoft.com/en-us/sql/odbc/reference/syntax/sqlsetconnectattr-function}
550
{SQLSetConnectAttr()} ODBC documentation.
551
552
\section3 How to Build the ODBC Plugin on Unix and \macos
553
554
It is recommended that you use unixODBC. You can find the latest
555
version and ODBC drivers at \l http://www.unixodbc.org.
556
You need the unixODBC header files and shared libraries.
557
558
Tell \c qt-cmake where to find the unixODBC header files and shared
559
libraries (here it is assumed that unixODBC is installed in
560
\c{/usr/local/unixODBC}) and build:
561
562
\snippet code/doc_src_sql-driver.qdoc 11
563
564
\section3 How to Build the ODBC Plugin on Windows
565
566
The ODBC header and include files should already be installed in the
567
right directories. You just have to build the plugin as follows:
568
569
\snippet code/doc_src_sql-driver.qdoc 12
570
571
\target QPSQL
572
\section2 QPSQL for PostgreSQL (Version 7.3 and above)
573
574
The QPSQL driver supports version 7.3 and higher of the PostgreSQL server.
575
576
For more information about PostgreSQL visit \l http://www.postgresql.org.
577
578
\section3 Timestamp Support
579
Since Qt 6.8, QDateTime values are converted to UTC before insertion
580
and back from UTC during retrieval. To make this work, the driver sets
581
the connection time zone to UTC during open() (SET TIME ZONE 'UTC').
582
Although PostgreSQL has the `timestamptz` column type, the timezone
583
used during insertion is not preserved and therefore all retrieved
584
QDateTime values are UTC.
585
586
\section3 QPSQL Unicode Support
587
588
The QPSQL driver automatically detects whether the PostgreSQL
589
database you are connecting to supports Unicode or not. Unicode is
590
automatically used if the server supports it. Note that the driver
591
only supports the UTF-8 encoding. If your database uses any other
592
encoding, the server must be compiled with Unicode conversion
593
support.
594
595
Unicode support was introduced in PostgreSQL version 7.1 and it will
596
only work if both the server and the client library have been compiled
597
with multibyte support. More information about how to set up a
598
multibyte enabled PostgreSQL server can be found in the PostgreSQL
599
Administrator Guide, Chapter 5.
600
601
\section3 QPSQL Case Sensitivity
602
603
PostgreSQL databases will only respect case sensitivity if the table or field
604
name is quoted when the table is created. So for example, a SQL query such
605
as:
606
607
\snippet code/doc_src_sql-driver.qdoc 39
608
609
will ensure that it can be accessed with the same case that was used. If the
610
table or field name is not quoted when created, the actual table name
611
or field name will be lower-case. When QSqlDatabase::record() or
612
QSqlDatabase::primaryIndex() access a table or field that was unquoted
613
when created, the name passed to the function must be lower-case to
614
ensure it is found. For example:
615
616
\snippet code/doc_src_sql-driver.qdoc 40
617
618
\section3 QPSQL Forward-only query support
619
620
To use forward-only queries, you must build the QPSQL plugin with
621
PostreSQL client library version 9.2 or later. If the plugin is
622
built with an older version, then forward-only mode will not be
623
available - calling QSqlQuery::setForwardOnly() with \c true will
624
have no effect.
625
626
\warning If you build the QPSQL plugin with PostgreSQL version 9.2 or later,
627
then you must distribute your application with libpq version 9.2 or later.
628
Otherwise, loading the QPSQL plugin will fail with the following message:
629
630
\snippet code/doc_src_sql-driver.qdoc 35
631
632
While navigating the results in forward-only mode, the handle of
633
QSqlResult may change. Applications that use the low-level handle of
634
SQL result must get a new handle after each call to any of QSqlResult
635
fetch functions. Example:
636
637
\snippet code/doc_src_sql-driver_snippet.cpp 36
638
639
While reading the results of a forward-only query with PostgreSQL,
640
the database connection cannot be used to execute other queries.
641
This is a limitation of libpq library. Example:
642
643
\snippet code/doc_src_sql-driver.cpp 37
644
645
This problem will not occur if query1 and query2 use different
646
database connections, or if we execute query2 after the while loop.
647
648
\note Some methods of QSqlDatabase like tables(), primaryIndex()
649
implicitly execute SQL queries, so these also cannot be used while
650
navigating the results of forward-only query.
651
652
\note QPSQL will print the following warning if it detects a loss of
653
query results:
654
655
\snippet code/doc_src_sql-driver.qdoc 38
656
657
\section3 Connection options
658
The Qt PostgreSQL plugin honors all connection options specified in the
659
\l {https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-PARAMKEYWORDS}
660
{connect()} PostgreSQL documentation.
661
662
\section3 How to Build the QPSQL Plugin on Unix and \macos
663
664
You need the PostgreSQL client library and headers installed.
665
666
To make \c qt-cmake find the PostgreSQL header files and shared
667
libraries, build the plugin the following way (assuming that the
668
PostgreSQL client is installed in \c{/usr/local/pgsql}):
669
670
\snippet code/doc_src_sql-driver.qdoc 13
671
672
\section3 How to Build the QPSQL Plugin on Windows
673
674
Install the appropriate PostgreSQL developer libraries for your
675
compiler. Assuming that PostgreSQL was installed in \c{C:\pgsql},
676
build the plugin as follows:
677
678
\snippet code/doc_src_sql-driver.qdoc 15
679
680
Users of MinGW may wish to consult the following online document:
681
\l{http://www.postgresql.org/docs/current/static/installation-platform-notes.html#INSTALLATION-NOTES-MINGW}{PostgreSQL MinGW/Native Windows}.
682
683
When you distribute your application, remember to include libpq.dll
684
in your installation package. It must be placed in the same folder
685
as the application executable.
686
687
\target QDB2
688
\section2 QDB2 for IBM DB2 (Version 7.1 and above)
689
690
The Qt DB2 plugin makes it possible to access IBM DB2 databases. It
691
has been tested with IBM DB2 v7.1 and 7.2. You must install the IBM
692
DB2 development client library, which contains the header and library
693
files necessary for compiling the QDB2 plugin.
694
695
The QDB2 driver supports prepared queries, reading/writing of Unicode
696
strings and reading/writing of BLOBs.
697
698
We suggest using a forward-only query when calling stored procedures
699
in DB2 (see QSqlQuery::setForwardOnly()).
700
701
\section3 Connection options
702
The Qt IBM DB2 plugin honors the following connection options:
703
\table
704
\header \li Attribute \li Possible value
705
\row
706
\li SQL_ATTR_ACCESS_MODE
707
\li SQL_MODE_READ_ONLY: open the database in read-only mode\br
708
SQL_MODE_READ_WRITE: open the database in read-write mode (default)
709
\row
710
\li SQL_ATTR_LOGIN_TIMEOUT
711
\li Number of seconds to wait for the database connection
712
during login (max: 32767, a value of 0 will wait forever)
713
\endtable
714
715
\section3 How to Build the QDB2 Plugin on Unix and \macos
716
717
\snippet code/doc_src_sql-driver.qdoc 18
718
719
\section3 How to Build the QDB2 Plugin on Windows
720
721
The DB2 header and include files should already be installed in the
722
right directories. You just have to build the plugin as follows:
723
724
\snippet code/doc_src_sql-driver.qdoc 20
725
726
\target QSQLITE
727
\section2 QSQLITE for SQLite (Version 3 and above)
728
729
The Qt SQLite plugin makes it possible to access SQLite
730
databases. SQLite is an in-process database, which means that it
731
is not necessary to have a database server. SQLite operates on a
732
single file, which must be set as the database name when opening
733
a connection. If the file does not exist, SQLite will try to
734
create it. SQLite also supports in-memory and temporary databases. Simply
735
pass respectively ":memory:" or an empty string as the database name.
736
737
SQLite has some restrictions regarding multiple users and
738
multiple transactions. If you try to read/write on a resource from different
739
transactions, your application might freeze until one transaction commits
740
or rolls back. The Qt SQLite driver will retry to write to a locked resource
741
until it runs into a timeout (see \c{QSQLITE_BUSY_TIMEOUT}
742
at QSqlDatabase::setConnectOptions()).
743
744
In SQLite any column, with the exception of an INTEGER PRIMARY KEY column,
745
may be used to store any type of value. For instance, a column declared as
746
INTEGER may contain an integer value in one row and a text value in the
747
next. This is due to SQLite associating the type of a value with the value
748
itself rather than with the column it is stored in. A consequence of this
749
is that the type returned by QSqlField::metaType() only indicates the field's
750
recommended type. No assumption of the actual type should be made from
751
this and the type of the individual values should be checked.
752
753
The driver is locked for updates while a select is executed. This
754
may cause problems when using QSqlTableModel because Qt's item views
755
fetch data as needed (with QSqlQuery::fetchMore() in the case of
756
QSqlTableModel).
757
758
You can find information about SQLite on \l{http://www.sqlite.org}.
759
760
\section3 Timestamp Support
761
SQLite does not have a special timestamp column type. A QDateTime is
762
stored as string, formatted in Qt::ISODateWithMs and therefore the
763
QDateTime timezone information is preserved during insertion and
764
select.
765
766
\section3 Connection options
767
The Qt SQLite plugin honors the following connection options:
768
\table
769
\header \li Attribute \li Possible value
770
\row
771
\li QSQLITE_BUSY_TIMEOUT
772
\li Busy handler timeout in milliseconds (val <= 0: disabled),
773
see \l {https://www.sqlite.org/c3ref/busy_timeout.html}
774
{SQLite documentation} for more information
775
776
\row
777
\li QSQLITE_USE_QT_VFS
778
\li If set, the database is opened using Qt's VFS which allows to
779
open databases using QFile. This way it can open databases from
780
any read-write locations (e.g.android shared storage) but also
781
from read-only resources (e.g. qrc or android assets). Be aware
782
that when opening databases from read-only resources make sure
783
you add QSQLITE_OPEN_READONLY attribute as well.
784
Otherwise it will fail to open it.
785
786
\row
787
\li QSQLITE_OPEN_READONLY
788
\li If set, the database is open in read-only mode which will fail
789
if no database exists. Otherwise the database will be opened in
790
read-write mode and created if the database file does not yet
791
exist (default)
792
\row
793
\li QSQLITE_OPEN_URI
794
\li The given filename is interpreted as an uri, see
795
\l {https://www.sqlite.org/c3ref/open.html} {SQLITE_OPEN_URI}
796
\row
797
\li QSQLITE_ENABLE_SHARED_CACHE
798
\li If set, the database is opened in
799
\l {https://www.sqlite.org/sharedcache.html} {shared cache mode},
800
otherwise in private cache mode
801
\row
802
\li QSQLITE_ENABLE_REGEXP
803
\li If set, the plugin defines a function 'regex' which can be used
804
in queries, QRegularExpression is used for evaluation of the regex query
805
\row
806
\li QSQLITE_NO_USE_EXTENDED_RESULT_CODES
807
\li Disables the usage of the \l {https://www.sqlite.org/c3ref/extended_result_codes.html}
808
{extended result code} feature in SQLite
809
\row
810
\li QSQLITE_ENABLE_NON_ASCII_CASE_FOLDING
811
\li If set, the plugin replaces the functions 'lower' and 'upper' with
812
QString functions for correct case folding of non-ascii characters
813
\row
814
\li QSQLITE_OPEN_NOFOLLOW
815
\li If set, the database filename is not allowed to contain a symbolic link
816
\endtable
817
818
\section3 How to Build the QSQLITE Plugin
819
820
SQLite version 3 is included as a third-party library within Qt.
821
It can be built by passing the \c{-DFEATURE_system_sqlite=OFF} parameter to the
822
\c qt-cmake command line.
823
824
If you do not want to use the SQLite library included with Qt, you
825
can pass \c{-DFEATURE_system_sqlite=ON} to the \c qt-cmake command
826
line to use the SQLite libraries of the operating system. This is
827
recommended whenever possible, as it reduces the installation size
828
and removes one component for which you need to track security
829
advisories.
830
831
On Unix and \macos (replace \c $SQLITE with the directory where
832
SQLite resides):
833
834
\snippet code/doc_src_sql-driver.qdoc 21
835
836
On Windows (assuming that SQLite is installed in \c{C:\SQLITE}):
837
838
\snippet code/doc_src_sql-driver.qdoc 23
839
840
\section3 Enable REGEXP operator
841
842
SQLite comes with a REGEXP operation. However the needed implementation must
843
be provided by the user. For convenience a default implementation can be
844
enabled by \l{QSqlDatabase::setConnectOptions()} {setting the connect
845
option} \c{QSQLITE_ENABLE_REGEXP} before \l{QSqlDatabase::open()} {the
846
database connection is opened}. Then a SQL statement like "column REGEXP
847
'pattern'" basically expands to the Qt code
848
849
\snippet code/doc_src_sql-driver.cpp 34
850
851
For better performance the regular expressions are cached internally. By
852
default the cache size is 25, but it can be changed through the option's
853
value. For example passing "\c{QSQLITE_ENABLE_REGEXP=10}" reduces the
854
cache size to 10.
855
856
\section3 QSQLITE File Format Compatibility
857
858
SQLite minor releases sometimes break file format forward compatibility.
859
For example, SQLite 3.3 can read database files created with SQLite 3.2,
860
but databases created with SQLite 3.3 cannot be read by SQLite 3.2.
861
Please refer to the SQLite documentation and change logs for information about
862
file format compatibility between versions.
863
864
Qt minor releases usually follow the SQLite minor releases, while Qt patch releases
865
follow SQLite patch releases. Patch releases are therefore both backward and forward
866
compatible.
867
868
To force SQLite to use a specific file format, it is necessary to build and
869
ship your own database plugin with your own SQLite library as illustrated above.
870
Some versions of SQLite can be forced to write a specific file format by setting
871
the \c{SQLITE_DEFAULT_FILE_FORMAT} define when building SQLite.
872
873
\target QMIMER
874
\section2 QMIMER for Mimer SQL version 11 and higher
875
876
The Qt Mimer SQL plugin makes it possible to work with the Mimer SQL RDBMS.
877
Mimer SQL provides small footprint, scalable and robust relational database
878
solutions that conform to international ISO SQL standards. Mimer SQL is available
879
on Windows, Linux, \macos, and OpenVMS as well as several embedded platforms like QNX, Android,
880
and embedded Linux.
881
882
Mimer SQL fully support Unicode. To work with Unicode data the column types National Character (NCHAR),
883
National Character Varying (NVARCHAR), or National Character Large Object (NCLOB) must be used.
884
For more information about Mimer SQL and unicode, see \l{https://developer.mimer.com/features/multilingual-support}
885
886
\section3 Timestamp Support
887
MimerSQL does not know anything about timezones and QDateTime
888
is used without honoring the timezone at all.
889
890
\note: This might change in the future.
891
892
\section3 QMIMER Stored Procedure Support
893
894
Mimer SQL have stored procedures according to the SQL standard (PSM) and
895
the plugin fully support IN, OUT, INOUT parameters as well as resultset procedures.
896
897
Example stored procedure with INOUT and OUT parameters:
898
899
\snippet code/doc_src_sql-driver.qdoc 44
900
901
Source code to access the INOUT and OUT values:
902
903
\snippet code/doc_src_sql-driver.cpp 40
904
905
\section3 How to Build the QMIMER Plugin on Unix and \macos
906
907
You need the Mimer SQL header files and shared libraries. Get them by installing
908
any of the Mimer SQL variants found at \l{https://developer.mimer.com}.
909
910
911
\snippet code/doc_src_sql-driver.qdoc 31
912
913
\section3 How to Build the QMIMER Plugin on Windows
914
915
You need the Mimer SQL header files and shared libraries. Get them by installing
916
any of the Mimer SQL variants found at \l{https://developer.mimer.com}.
917
918
\snippet code/doc_src_sql-driver.qdoc 32
919
920
\target QIBASE
921
\section2 QIBASE for Borland InterBase
922
923
The Qt InterBase plugin makes it possible to access the InterBase and
924
Firebird databases. InterBase can either be used as a client/server or
925
without a server in which case it operates on local files. The
926
database file must exist before a connection can be established. Firebird
927
must be used with a server configuration.
928
929
Note that InterBase requires you to specify the full path to the
930
database file, no matter whether it is stored locally or on another
931
server.
932
933
\section3 Timestamp Support
934
Interbase stores timestamps in UTC without any timezone information.
935
Due to this, the QDateTime is used without honoring the timezone at all.
936
937
Since Firebird 4.0, the database supports timestamps with timezones. The
938
timezone information is stored separately to the timestamp so it can
939
be properly retrieved later on. See the Firebird
940
\l {https://firebirdsql.org/file/documentation/chunk/en/refdocs/fblangref40/fblangref40-datatypes-datetime.html}
941
{documentation} for more information about timestamp handling.
942
943
\section3 Connection options
944
The Qt Borland InterBase plugin honors the following connection options:
945
\table
946
\header \li Attribute \li Possible value
947
\row
948
\li ISC_DPB_SQL_ROLE_NAME
949
\li Specifies the login role name
950
\endtable
951
952
953
\section3 How to Build the QIBASE Plugin
954
\snippet code/doc_src_sql-driver.cpp 24
955
956
You need the InterBase/Firebird development headers and libraries
957
to build this plugin.
958
959
Due to license incompatibilities with the GPL, users of the Qt Open Source
960
Edition are not allowed to link this plugin to the commercial editions of
961
InterBase. Please use Firebird or the free edition of InterBase.
962
963
\section3 QIBASE Stored procedures
964
965
InterBase/Firebird return OUT values as result set, so when calling stored
966
procedure, only IN values need to be bound via QSqlQuery::bindValue(). The
967
RETURN/OUT values can be retrieved via QSqlQuery::value(). Example:
968
969
\snippet code/doc_src_sql-driver.cpp 26
970
971
\section3 How to Build the QIBASE Plugin on Unix and \macos
972
973
The following assumes InterBase or Firebird is installed in
974
\c{/opt/interbase}:
975
976
If you are using InterBase:
977
978
\snippet code/doc_src_sql-driver.qdoc 27
979
980
Optionally, use the CMake variables \c{Interbase_INCLUDE_DIR} and
981
\c{Interbase_LIBRARY} to specify the include path and library directly.
982
983
\section3 How to Build the QIBASE Plugin on Windows
984
985
The following assumes InterBase or Firebird is installed in
986
\c{C:\interbase}:
987
988
If you are using InterBase:
989
990
\snippet code/doc_src_sql-driver.qdoc 29
991
992
Optionally, use the CMake variables \c{Interbase_INCLUDE_DIR} and
993
\c{Interbase_LIBRARY} to specify the include path and library directly.
994
995
Note that \c{C:\interbase\bin} must be in the \c PATH.
996
997
\target troubleshooting
998
\section1 Troubleshooting
999
1000
You should always use client libraries that have been compiled with
1001
the same compiler as you are using for your project. If you cannot get
1002
a source distribution to compile the client libraries yourself, you
1003
must make sure that the pre-compiled library is compatible with
1004
your compiler, otherwise you will get a lot of "undefined symbols"
1005
errors.
1006
1007
If the compilation of a plugin succeeds but it cannot be loaded
1008
afterwards, check out the following steps to find out the culprit:
1009
1010
\list 1
1011
\li Ensure that the plugin is in the correct directory. You can use
1012
QApplication::libraryPaths() to determine where Qt looks for plugins.
1013
\li Ensure that the client libraries of the DBMS are available on the
1014
system. On Unix, run the command \c{ldd} and pass the name of the
1015
plugin as parameter, for example \c{ldd libqsqlmysql.so}. You will
1016
get a warning if any of the client libraries could not be found.
1017
On Windows, you can use Visual Studio's dependency walker or
1018
\l{https://github.com/lucasg/Dependencies/releases}{Dependencies GUI}
1019
to find out the dependent libraries. With
1020
Qt Creator, you can update the \c PATH environment variable in the
1021
\gui Run section of the \gui Project panel to include the path to
1022
the folder containing the client libraries.
1023
\li When using MSVC, also make sure the plugin is built with the correct
1024
build type. Due to different MSVC runtimes for debug and release,
1025
a Qt debug build can't load a Qt release plugin and vice versa.
1026
\li Run the compiled Qt executable with the environment variable
1027
\l{Environment Variables Recognized by Qt}{QT_DEBUG_PLUGINS} set
1028
to get very verbose debug output when loading plugins.
1029
\li To retrieve possible debug messages from the SQL subsystem, enable
1030
the output by setting the environment variable \c{QT_LOGGING_RULES}
1031
to \c{qt.sql.*.debug=true}. Don't forget to enable the
1032
\l{Environment Variables Recognized by Qt}{console} when working on
1033
windows.
1034
See \l{Logging Rules} for a more detailed explanation on how to set
1035
logging rules.
1036
\endlist
1037
1038
Make sure you have followed the guide to \l{Deploying Plugins}.
1039
1040
\target development
1041
\section1 How to Write Your Own Database Driver
1042
1043
QSqlDatabase is responsible for loading and managing database driver
1044
plugins. When a database is added (see QSqlDatabase::addDatabase()),
1045
the appropriate driver plugin is loaded (using QSqlDriverPlugin).
1046
QSqlDatabase relies on the driver plugin to provide interfaces for
1047
QSqlDriver and QSqlResult.
1048
1049
QSqlDriver is an abstract base class which defines the functionality
1050
of a SQL database driver. This includes functions such as
1051
QSqlDriver::open() and QSqlDriver::close(). QSqlDriver is responsible
1052
for connecting to a database, establish the proper environment, etc.
1053
In addition, QSqlDriver can create QSqlQuery objects appropriate for
1054
the particular database API. QSqlDatabase forwards many of its
1055
function calls directly to QSqlDriver which provides the concrete
1056
implementation.
1057
1058
QSqlResult is an abstract base class which defines the functionality
1059
of a SQL database query. This includes statements such as \c{SELECT},
1060
\c{UPDATE}, and \c{ALTER} \c{TABLE}. QSqlResult contains functions
1061
such as QSqlResult::next() and QSqlResult::value(). QSqlResult is
1062
responsible for sending queries to the database, returning result
1063
data, etc. QSqlQuery forwards many of its function calls directly to
1064
QSqlResult which provides the concrete implementation.
1065
1066
QSqlDriver and QSqlResult are closely connected. When implementing a
1067
Qt SQL driver, both of these classes must to be subclassed and the
1068
abstract virtual methods in each class must be implemented.
1069
1070
To implement a Qt SQL driver as a plugin (so that it is
1071
recognized and loaded by the Qt library at runtime), the driver
1072
must use the Q_PLUGIN_METADATA() macro. Read \l{How to Create Qt
1073
Plugins} for more information on this. You can also check out how
1074
this is done in the SQL plugins that are provided with Qt in
1075
\c{QTDIR/qtbase/src/plugins/sqldrivers}.
1076
1077
The following code can be used as a skeleton for a SQL driver:
1078
1079
\snippet sqldatabase/sqldatabase.cpp 47
1080
\codeline
1081
\snippet sqldatabase/sqldatabase.cpp 48
1082
*/
qtbase
src
sql
doc
src
sql-driver.qdoc
Generated on
for Qt by
1.16.1