diff options
Diffstat (limited to 'doc/src/sql-programming')
-rw-r--r-- | doc/src/sql-programming/qsqldatatype-table.qdoc | 583 | ||||
-rw-r--r-- | doc/src/sql-programming/sql-driver.qdoc | 762 | ||||
-rw-r--r-- | doc/src/sql-programming/sql-programming.qdoc | 614 |
3 files changed, 1959 insertions, 0 deletions
diff --git a/doc/src/sql-programming/qsqldatatype-table.qdoc b/doc/src/sql-programming/qsqldatatype-table.qdoc new file mode 100644 index 0000000..e8c2351 --- /dev/null +++ b/doc/src/sql-programming/qsqldatatype-table.qdoc @@ -0,0 +1,583 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the documentation of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain +** additional rights. These rights are described in the Nokia Qt LGPL +** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this +** package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 3.0 as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU General Public License version 3.0 requirements will be +** met: http://www.gnu.org/copyleft/gpl.html. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at http://qt.nokia.com/contact. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +/*! + \page sql-types.html + \title Recommended Use of Data Types in Databases + + \ingroup best-practices + + \section1 Recommended Use of Types in Qt Supported Databases + + This table shows the recommended data types used when extracting data + from the databases supported in Qt. It is important to note that the + types used in Qt are not necessarily valid as input to the specific + database. One example could be that a double would work perfectly as + input for floating point records in a database, but not necessarily + as a storage format for output from the database since it would be stored + with 64-bit precision in C++. + + \tableofcontents + + \section2 IBM DB2 Data Types + + \table 90% + \header + \o IBM DB2 data type + \o SQL type description + \o Recommended input (C++ or Qt data type) + \row + \o SMALLINT + \o 16-bit signed integer + \o typedef qint16 + \row + \o INTEGER + \o 32-bit signed integer + \o typedef qint32 + \row + \o BIGINT + \o 64-bit signed integer + \o typedef qint64 + \row + \o REAL + \o 32-bit Single-precision floating point + \o By default mapping to QString + \row + \o DOUBLE PRECISION + \o 64-bit Double-precision floating point + \o By default mapping to QString + \row + \o FLOAT + \o 64-bit Double-precision floating point + \o By default mapping to QString + \row + \o CHAR + \o Fixed-length, null-terminated character string + \o Mapped to QString + \row + \o VARCHAR + \o Null-terminated varying length string + \o Mapped to QString + \row + \o LONG VARCHAR + \o Not null-terminated varying length character string + \o Mapped to QString + \row + \o BLOB + \o Not null-terminated varying binary string with 4-byte string + length indicator + \o Mapped to QByteArray + \row + \o CLOB + \o Character large string object + \o Mapped to QString + \row + \o DATE + \o Null-terminated character string of the following format: + yyyy-mm-dd + \o Mapped to QDate + \row + \o TIME + \o Null-terminated character string of the following format: hh.mm.ss + \o Mapped to QTime + \row + \o TIMESTAMP + \o Null-terminated character string of the following format: yyyy-mm-dd-hh.mm.ss.nnnnnn + \o Mapped to QDateTime + \endtable + + \section2 Borland InterBase Data Types + + \table 90% + \header + \o Borland InterBase data type + \o SQL type description + \o Recommended input (C++ or Qt data type) + \row + \o BOOLEAN + \o Boolean + \o bool + \row + \o TINYINT + \o 8 bit signed integer + \o typedef qint8 + \row + \o SMALLINT + \o 16-bit signed integer + \o typedef qint16 + \row + \o INTEGER + \o 32-bit signed integer + \o typedef qint32 + \row + \o BIGINT LONG + \o 64-bit signed integer + \o typedef qint64 + \row + \o REAL FLOAT + \o 32-bit floating point + \o By default mapping to QString + \row + \o FLOAT + \o 64-bit floating point + \o By default mapping to QString + \row + \o DOUBLE + \o 64-bit floating point + \o By default mapping to QString + \row + \o DOUBLE PRECISION + \o 64-bit Double-precision floating point + \o By default mapping to QString + \row + \o VARCHAR STRING + \o Character string, Unicode + \o Mapped to QString + \row + \o CLOB + \o Character large string object + \o Mapped to QString + \row + \o DATE + \o Displays date. Format: 'yyyy-mm-dd' + \o Mapped to QDate + \row + \o TIME + \o Displays time. Format is 'hh:mm:ss' in 24-hour format + \o Mapped to QTime + \row + \o TIMESTAMP + \o Displays a timestamp. Format is 'yyyy-mm-dd hh:mm:ss' + \o Mapped to QDateTime + \endtable + + \section2 MySQL Data Types + + \table 90% + \header + \o MySQL data type + \o SQL type description + \o Recommended input (C++ or Qt data type) + \row + \o TINYINT + \o 8 bit signed integer + \o typedef qint8 + \row + \o TINYINT UNSIGNED + \o 8 bit unsigned integer + \o typedef quint8 + \row + \o SMALLINT + \o 16-bit signed integer + \o typedef qint16 + \row + \o SMALLINT UNSIGNED + \o 16-bit unsigned integer + \o typedef quint16 + \row + \o INT + \o 32-bit signed integer + \o typedef qint32 + \row + \o INT UNSIGNED + \o 32-bit unsigned integer + \o typedef quint32 + \row + \o BIGINT + \o 64-bit signed integer + \o typedef qint64 + \row + \o FLOAT + \o 32-bit Floating Point + \o By default mapping to QString + \row + \o DOUBLE + \o 64-bit Floating Point + \o By default mapping to QString + \row + \o CHAR + \o Character string + \o Mapped to QString + \row + \o VARCHAR + \o Character string + \o Mapped to QString + \row + \o TINYTEXT + \o Character string + \o Mapped to QString + \row + \o TEXT + \o Character string + \o Mapped to QString + \row + \o MEDIUMTEXT + \o Character string + \o Mapped to QString + \row + \o LONGTEXT + \o Character string + \o Mapped to QString + \row + \o CLOB + \o Character large string object + \o Mapped to QString + \row + \o all BLOB types + \o BLOB + \o Mapped to QByteArray + \row + \o DATE + \o Date without Time + \o Mapped to QDate + \row + \o DATETIME + \o Date and Time + \o Mapped to QDateTime + \row + \o TIMESTAMP + \o Date and Time + \o Mapped to QDateTime + \row + \o TIME + \o Time + \o Mapped to QTime + \row + \o YEAR + \o Year (int) + \o Mapped to QDateTime + \row + \o ENUM + \o Enumeration of Value Set + \o Mapped to QString + \endtable + + \section2 Oracle Call Interface Data Types + + \table 90% + \header + \o Oracle Call Interface data type + \o SQL type description + \o Recommended input (C++ or Qt data type) + \row + \o NUMBER + \o FLOAT, DOUBLE, PRECISIONc REAL + \o By default mapping to QString + \row + \o NUMBER(38) + \o INTEGER INT SMALLINT + \o typedef qint8/16/32/64 + \row + \o NUMBER(p,s) + \o NUMERIC(p,s) DECIMAL(p,s)a + \o By default mapping to QString + \row + \o NVARCHAR2(n) + \o Character string (NATIONAL CHARACTER VARYING(n) NATIONAL + CHAR VARYING(n) NCHAR VARYING(n)) + \o Mapped to QString + \row + \o NCHAR(n) + \o Character string (NATIONAL CHARACTER(n) NATIONAL CHAR(n) + NCHAR(n)) + \o Mapped to QString + \row + \o CHAR(n) + \o Character string (CHARACTER(n) CHAR(n)) + \o Mapped to QString + \row + \o CLOB + \o Character large string object + \o Mapped to QString + \row + \o BLOB + \o A binary large object + \o Mapped to QByteArray + \row + \o TIMESTAMP + \o Year, month, and day values of date, as well as hour, minute, + and second values of time + \o Mapped to QDateTime + \endtable + + \section2 ODBC Data Types + + \table 90% + \header + \o ODBC data type + \o SQL type description + \o Recommended input (C++ or Qt data type) + \row + \o BIT + \o Boolean + \o BOOL + \row + \o TINYINT + \o 8 bit integer + \o typedef qint8 + \row + \o SMALLINT + \o 16-bit signed integer + \o typedef qint16 + \row + \o INTEGER + \o 32-bit signed integer + \o typedef qint32 + \row + \o BIGINT + \o 64-bit signed integer + \o typedef qint64 + \row + \o REAL + \o 32-bit Single-precision floating point + \o By default mapping to QString + \row + \o FLOAT + \o 64-bit Double floating point + \o By default mapping to QString + \row + \o DOUBLE + \o 64-bit Double floating point + \o By default mapping to QString + \row + \o CHAR + \o Character string + \o Mapped to QString + \row + \o VARCHAR + \o Character string + \o Mapped to QString + \row + \o LONGVARCHAR + \o Character string + \o Mapped to QString + \row + \o CLOB + \o Character large string object + \o Mapped to QString + \row + \o DATE + \o Character string + \o Mapped to QDate + \row + \o TIME + \o Character Time, Character string + \o Mapped to QTime + \row + \o TIMESTAMP + \o Character Time, Character string + \o Mapped to QDateTime + \endtable + + \section2 PostgreSQL Data Types + + \table 90% + \header + \o PostgreSQL data type + \o SQL type description + \o Recommended input (C++ or Qt data type) + \row + \o BOOLEAN + \o Boolean + \o bool + \row + \o SMALLINT + \o 16-bit signed integer + \o typedef qint16 + \row + \o INTEGER + \o 32-bit signed integer + \o typedef qint32 + \row + \o BIGINT + \o 64-bit signed integer + \o typedef qint64 + \row + \o REAL + \o 32-bit variable-precision floating point + \o By default mapping to QString + \row + \o DOUBLE PRECISION + \o 64-bit variable-precision floating point + \o By default mapping to QString + \row + \o DECIMAL VARIABLE + \o user-specified precision, exact + \o Mapped to QString + \row + \o NUMERIC VARIABLE + \o user-specified precision, exact + \o Mapped to QString + \row + \o VARCHAR + \o variable-length character string + \o Mapped to QString + \row + \o CHARACTER + \o Character string of fixed-length + \o Mapped to QString + \row + \o TEXT + \o Character string of variable-length + \o Mapped to QString + \row + \o CLOB + \o Character large string object + \o Mapped to QString + \row + \o TIMESTAMP + \o 8 bytes, both date and time + \o Mapped to QDateTime + \row + \o TIMESTAMP + \o 8 bytes, both date and time, with time zone + \o Mapped to QDateTime + \row + \o DATE + \o 4 bytes, dates only + \o Mapped to QDate + \row + \o TIME + \o 8 bytes, times of day only 00:00:00.00 - 23:59:59.99 + \o Mapped to QTime + \row + \o TIME + \o 12 bytes times of day only, with time zone 00:00:00.00+12 + \o Mapped to QDateTime + \endtable + + \section2 QSQLITE SQLite version 3 Data Types + + \table 90% + \header + \o QSQLITE SQLite version 3 data type + \o SQL type description + \o Recommended input (C++ or Qt data type) + \row + \o NULL + \o NULL value. + \o NULL + \row + \o INTEGER + \o Signed integer, stored in 8, 16, 24, 32, 48, or 64-bits + depending on the magnitude of the value. + \o typedef qint8/16/32/64 + \row + \o REAL + \o 64-bit floating point value. + \o By default mapping to QString + \row + \o TEXT + \o Character string (UTF-8, UTF-16BE or UTF-16-LE). + \o Mapped to QString + \row + \o CLOB + \o Character large string object + \o Mapped to QString + \row + \o BLOB + \o The value is a BLOB of data, stored exactly as it was input. + \o Mapped to QByteArray + \endtable + + \section2 Sybase Adaptive Server Data Types + + \table 90% + \header + \o Sybase Adaptive Server data type + \o SQL type description + \o Recommended input (C++ or Qt data type) + \row + \o BINARY + \o Describes a fixed-length binary value up to 255 bytes in size. + \o Mapped to QByteArray + \row + \o CHAR + \o Character String + \o Mapped to QString + \row + \o DATETIME + \o Date and time. Range: 1753-01-01 00:00:00 through 9999-12-31 23:59:59. + \o Mapped to QDateTime + \row + \o NCHAR + \o Character String of fixed length + \o Mapped to QString + \row + \o NVARACHAR + \o Character String of variable length + \o Mapped to QString + \row + \o VARCHAR + \o Character String of fixed length + \o Mapped to QString + \row + \o CLOB + \o Character large string object + \o Mapped to QString + \row + \o TIMESTAMP + \o A unique number within a database + \o Mapped to QString + \row + \o SMALLDATETIME + \o Date and time. Range: 1900-01-01 00:00 through 2079-12-31 23:59 + \o Mapped to QDateTime + \row + \o UNICHAR + \o Character String of fixed length.(Unicode) + \o Mapped to QString + \row + \o UNIVARCHAR + \o Character String of variable length.(Unicode) + \o Mapped to QString + \row + \o VARBINARY + \o Describes a variable-length binary value up to 255 bytes in size + \o Mapped to QByteArray + \endtable + + \section2 SQLite Version 2 + + SQLite version 2 is "typeless". This means that you can store any kind of + data you want in any column of any table, regardless of the declared + data type of that column. We recommend that you map the data to QString. +*/ diff --git a/doc/src/sql-programming/sql-driver.qdoc b/doc/src/sql-programming/sql-driver.qdoc new file mode 100644 index 0000000..832fd0c --- /dev/null +++ b/doc/src/sql-programming/sql-driver.qdoc @@ -0,0 +1,762 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the documentation of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain +** additional rights. These rights are described in the Nokia Qt LGPL +** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this +** package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 3.0 as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU General Public License version 3.0 requirements will be +** met: http://www.gnu.org/copyleft/gpl.html. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at http://qt.nokia.com/contact. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +/*! + \page sql-driver.html + \title SQL Database Drivers + \brief How to configure and install QtSql drivers for supported databases. + + \ingroup best-practices + + The QtSql module uses driver \l{How to Create Qt + Plugins}{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 + \l{#development}{writing your own drivers}. + + \tableofcontents + + \section1 Supported Databases + + The table below lists the drivers included with Qt. Due to + license incompatibilities with the GPL, not all of the plugins + are provided with Open Source Versions of Qt. + + \table + \header \o Driver name \o DBMS + \row \o \link #QDB2 QDB2\endlink \o IBM DB2 (version 7.1 and above) + \row \o \link #QIBASE QIBASE\endlink \o Borland InterBase + \row \o \link #QMYSQL QMYSQL\endlink \o MySQL + \row \o \link #QOCI QOCI\endlink \o Oracle Call Interface Driver + \row \o \link #QODBC QODBC\endlink + \o Open Database Connectivity (ODBC) - Microsoft SQL Server and other + ODBC-compliant databases + \row \o \link #QPSQL QPSQL\endlink \o PostgreSQL (versions 7.3 and above) + \row \o \link #QSQLITE2 QSQLITE2\endlink \o SQLite version 2 + \row \o \link #QSQLITE QSQLITE\endlink \o SQLite version 3 + \row \o \link #QTDS QTDS\endlink \o Sybase Adaptive Server + \endtable + + \bold{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. + + \target building + \section1 Building the Drivers Using Configure + + On Unix and Mac OS X, the Qt \c configure script tries to + automatically detect the available client libraries on your + machine. Run \c{configure -help} to see what drivers can be + built. You should get an output similar to this: + + \snippet doc/src/snippets/code/doc_src_sql-driver.qdoc 0 + + The \c configure script cannot detect the neccessary libraries + and include files if they are not in the standard paths, so it + may be necessary to specify these paths using the \c -I and \c -L + command-line options. For example, if your MySQL include files + are installed in \c /usr/local/mysql (or in \c{C:\mysql\include} + on Windows), then pass the following parameter to configure: \c + -I/usr/local/mysql (or \c{-I C:\mysql\include} for Windows). + + On Windows the \c -I parameter doesn't accept spaces in + filenames, so use the 8.3 name instead; for example, use + \c{C:\progra~1\mysql} instead of \c{C:\Program Files\mysql}. + + Use the \c{-qt-sql-<driver>} parameter to build the database driver + statically into your Qt library or \c{-plugin-sql-<driver>} to build + the driver as a plugin. Look at the sections that follow for + additional information about required libraries. + + \target buildingmanually + \section1 Building the Plugins Manually + + \target QMYSQL + \section2 QMYSQL for MySQL 4 and higher + + \section3 QMYSQL Stored Procedure Support + + MySQL 5 introduces 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(). + + Example stored procedure: + + \snippet doc/src/snippets/code/doc_src_sql-driver.qdoc 1 + + Source code to access the OUT values: + + \snippet doc/src/snippets/code/doc_src_sql-driver.qdoc 2 + + \bold{Note:} \c{@outval1} and \c{@outval2} are variables local to the current + connection and will not be affected by queries sent from another host + or connection. + + \section3 Embedded MySQL Server + + 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. + + To use the embedded MySQL server, simply link the Qt plugin to \c + libmysqld instead of libmysqlclient. This can be done by replacing + \c -lmysqlclient_r by \c -lmysqld in the \c qmake command in the + section below. + + Please refer to the MySQL documentation, chapter "libmysqld, the Embedded + MySQL Server Library" for more information about the MySQL embedded server. + + \section3 How to Build the QMYSQL Plugin on Unix and Mac OS X + + You need the MySQL header files and as well as the shared library + \c{libmysqlclient.so}. Depending on your Linux distribution you may + need to install a package which is usually called "mysql-devel". + + Tell \l qmake where to find the MySQL header files and shared + libraries (here it is assumed that MySQL is installed in + \c{/usr/local}) and run \c{make}: + + \snippet doc/src/snippets/code/doc_src_sql-driver.qdoc 3 + + After installing Qt, as described in the \l{Installing Qt on X11 + Platforms} document, you also need to install the plugin in the + standard location: + + \snippet doc/src/snippets/code/doc_src_sql-driver.qdoc 4 + + \section3 How to Build the QMYSQL Plugin on Windows + + You need to get the MySQL installation files. Run \c SETUP.EXE and + choose "Custom Install". Install the "Libs & Include Files" Module. + Build the plugin as follows (here it is assumed that MySQL is + installed in \c{C:\MySQL}): + + \snippet doc/src/snippets/code/doc_src_sql-driver.qdoc 5 + + If you are not using a Microsoft compiler, replace \c nmake with \c + make in the line above. + + \note This database plugin is not supported for Windows CE. + + \note Including \c{"-o Makefile"} as an argument to \l qmake to + tell it where to build the makefile can cause the plugin to be + built in release mode only. If you are expecting a debug version + to be built as well, don't use the \c{"-o Makefile"} option. + + \target QOCI + \section2 QOCI for the Oracle Call Interface (OCI) + + \section3 General Information about the OCI plugin + + The Qt OCI plugin supports Oracle 9i, 10g and higher. After + connecting to the Oracle server, the plugin will auto-detect the + database version and enable features accordingly. + + 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. + + \section3 OCI User Authentication + + 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. + + Leave the username and password empty when opening a connection with + QSqlDatabase to use the external credentials authentication. + + \section3 OCI BLOB/LOB Support + + Binary Large Objects (BLOBs) can be read and written, but be aware + that this process may require a lot of memory. You should use a forward + only query to select LOB fields (see QSqlQuery::setForwardOnly()). + + Inserting BLOBs should be done using either a prepared query where the + BLOBs are bound to placeholders or QSqlTableModel, which uses a prepared + query to do this internally. + + \section3 How to Build the OCI Plugin on Unix and Mac OS X + + For Oracle 10g, all you need is the "Instant Client Package - Basic" and + "Instant Client Package - SDK". For Oracle prior to 10g, you require + the standard Oracle client and the SDK packages. + + Oracle library files required to build the driver: + + \list + \i \c libclntsh.so (all versions) + \i \c libwtc9.so (only Oracle 9) + \endlist + + Tell \c qmake where to find the Oracle header files and shared + libraries and run make: + + For Oracle version 9: + \snippet doc/src/snippets/code/doc_src_sql-driver.qdoc 6 + + For Oracle version 10, we assume that you installed the RPM packages of the + Instant Client Package SDK (you need to adjust the version number accordingly): + \snippet doc/src/snippets/code/doc_src_sql-driver.qdoc 7 + + \bold{Note:} If you are using the Oracle Instant Client package, + you will need to set LD_LIBRARY_PATH when building the OCI SQL plugin + and when running an applicaiton that uses the OCI SQL plugin. You can + avoid this requirement by setting and RPATH and listing all of the + libraries to link to. Here is an example: + \snippet doc/src/snippets/code/doc_src_sql-driver.qdoc 32 + + If you wish to build the OCI plugin manually with this method the procedure looks like this: + \snippet doc/src/snippets/code/doc_src_sql-driver.qdoc 33 + + \section3 How to Build the OCI Plugin on Windows + + Choosing the option "Programmer" in the Oracle Client Installer from + the Oracle Client Installation CD is sufficient to build the plugin. + + Build the plugin as follows (here it is assumed that Oracle Client is + installed in \c{C:\oracle}): + + \snippet doc/src/snippets/code/doc_src_sql-driver.qdoc 8 + + If you are not using a Microsoft compiler, replace \c nmake with \c + make in the line above. + + When you run your application you will also need to add the \c oci.dll + path to your \c PATH environment variable: + + \snippet doc/src/snippets/code/doc_src_sql-driver.qdoc 9 + + \bold{Note:} This database plugin is not supported for Windows CE. + + \target QODBC + \section2 QODBC for Open Database Connectivity (ODBC) + + \section3 General Information about the ODBC plugin + + 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. + + \bold{Note:} You should use native drivers in preference to the ODBC + driver where they are available. ODBC support can be used as a fallback + for compliant databases if no native drivers are available. + + 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 client that uses your application is + required to have an ODBC driver manager installed, otherwise the + QODBC plugin will not work. + + Be aware that when connecting to an ODBC datasource you must pass in + the name of the ODBC datasource to the QSqlDatabase::setDatabaseName() + function rather than the actual database name. + + The QODBC Plugin needs an ODBC compliant driver manager version 2.0 or + later to work. Some ODBC drivers claim to be version 2.0 compliant, + but do not offer all the necessary functionality. The QODBC plugin + therefore checks whether the data source can be used after a + connection has been established and refuses to work if the check + fails. If you don't like this behavior, you can remove the \c{#define + ODBC_CHECK_DRIVER} line from the file \c{qsql_odbc.cpp}. Do this at + your own risk! + + By default, Qt instructs the ODBC driver to behave as an ODBC 2.x + driver. However, for some \e{driver-manager/ODBC 3.x-driver} + combinations (e.g., \e{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 + \l{QSqlDatabase::setConnectOptions()} {setting the connect option} + \c{"SQL_ATTR_ODBC_VERSION=SQL_OV_ODBC3"} before you + \l{QSqlDatabase::open()} {open your database connection}. Note + that this will affect multiple aspects of ODBC driver behavior, + e.g., the SQLSTATEs. Before setting this connect option, consult + your ODBC documentation about behavior differences you can expect. + + If you experience very slow access of the ODBC datasource, make sure + that ODBC call tracing is turned off in the ODBC datasource manager. + + Some drivers don't support scrollable cursors. In that case case only + queries in forwardOnly mode can be used successfully. + + \section3 ODBC Stored Procedure Support + + 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 \e forward using \l QSqlQuery::setForwardOnly(). + + \snippet doc/src/snippets/code/doc_src_sql-driver.qdoc 10 + + \bold{Note:} The value returned by the stored procedure's return statement + is discarded. + + \section3 ODBC Unicode Support + + The QODBC Plugin will use the Unicode API if UNICODE is defined. On + Windows NT based systems, this is the default. Note that the ODBC + driver and the DBMS must also support Unicode. + + Some driver managers and drivers don't support UNICODE. To use the + QODBC plugin with such drivers it has to be compiled with the + Q_ODBC_VERSION_2 defined. + + For the Oracle 9 ODBC driver (Windows), it is neccessary to check + "SQL_WCHAR support" in the ODBC driver manager otherwise Oracle + will convert all Unicode strings to local 8-bit. + + \section3 How to Build the ODBC Plugin on Unix and Mac OS X + + It is recommended that you use unixODBC. You can find the latest + version and ODBC drivers at \l http://www.unixodbc.org. + You need the unixODBC header files and shared libraries. + + Tell \c qmake where to find the unixODBC header files and shared + libraries (here it is assumed that unixODBC is installed in + \c{/usr/local/unixODBC}) and run \c{make}: + + \snippet doc/src/snippets/code/doc_src_sql-driver.qdoc 11 + + \section3 How to Build the ODBC Plugin on Windows + + The ODBC header and include files should already be installed in the + right directories. You just have to build the plugin as follows: + + \snippet doc/src/snippets/code/doc_src_sql-driver.qdoc 12 + + If you are not using a Microsoft compiler, replace \c nmake with \c + make in the line above. + + \bold{Note:} This database plugin is not officially supported for Windows CE. + + \target QPSQL + \section2 QPSQL for PostgreSQL (Version 7.3 and Above) + + \section3 General Information about the QPSQL driver + + The QPSQL driver supports version 7.3 and higher of the PostgreSQL server. + We recommend that you use a client library from version 7.3.15, 7.4.13, + 8.0.8, 8.1.4 or more recent as these versions contain security fixes, and + as the QPSQL driver might not build with older versions of the client + library depending on your platform. + + For more information about PostgreSQL visit \l http://www.postgresql.org. + + \section3 QPSQL Unicode Support + + The QPSQL driver automatically detects whether the PostgreSQL + database you are connecting to supports Unicode or not. Unicode is + automatically used if the server supports it. Note that the driver + only supports the UTF-8 encoding. If your database uses any other + encoding, the server must be compiled with Unicode conversion + support. + + Unicode support was introduced in PostgreSQL version 7.1 and it will + only work if both the server and the client library have been compiled + with multibyte support. More information about how to set up a + multibyte enabled PostgreSQL server can be found in the PostgreSQL + Administrator Guide, Chapter 5. + + \section3 QPSQL BLOB Support + + Binary Large Objects are supported through the \c BYTEA field type in + PostgreSQL server versions >= 7.1. + + \section3 How to Build the QPSQL Plugin on Unix and Mac OS X + + You need the PostgreSQL client library and headers installed. + + To make \c qmake find the PostgreSQL header files and shared + libraries, run \c qmake the following way (assuming that the + PostgreSQL client is installed in \c{/usr}): + + \snippet doc/src/snippets/code/doc_src_sql-driver.qdoc 13 + + After installing Qt, as described in the \l{Installing Qt on X11 Platforms} document, + you also need to install the plugin in the standard location: + + \snippet doc/src/snippets/code/doc_src_sql-driver.qdoc 14 + + \section3 How to Build the QPSQL Plugin on Windows + + Install the appropriate PostgreSQL developer libraries for your + compiler. Assuming that PostgreSQL was installed in \c{C:\psql}, + build the plugin as follows: + + \snippet doc/src/snippets/code/doc_src_sql-driver.qdoc 15 + + Users of MinGW may wish to consult the following online document: + \l{Compiling PostgreSQL On Native Win32 FAQ}. + + \bold{Note:} This database plugin is not supported for Windows CE. + + \target QTDS + \section2 QTDS for Sybase Adaptive Server + \section3 General Information about QTDS + + It is not possible to set the port with QSqlDatabase::setPort() due to limitations in the + Sybase client library. Refer to the Sybase documentation for information on how to set up + a Sybase client configuration file to enable connections to databases on non-default ports. + + \section3 How to Build the QDTS Plugin on Unix and Mac OS X + + Under Unix, two libraries are available which support the TDS protocol: + + \list + \i FreeTDS, a free implementation of the TDS protocol + (\l{http://www.freetds.org}). Note that FreeTDS is not yet stable, + so some functionality may not work as expected. + + \i Sybase Open Client, available from \l{http://www.sybase.com}. + Note for Linux users: Get the Open Client RPM from + \l{http://linux.sybase.com}. + \endlist + + Regardless of which library you use, the shared object file + \c{libsybdb.so} is needed. Set the \c SYBASE environment variable to + point to the directory where you installed the client library and + execute \c{qmake}: + + \snippet doc/src/snippets/code/doc_src_sql-driver.qdoc 16 + + \section3 How to Build the QDTS Plugin on Windows + + You can either use the DB-Library supplied by Microsoft or the Sybase + Open Client (\l{http://www.sybase.com}). You must include \c + NTWDBLIB.LIB to build the plugin: + + \snippet doc/src/snippets/code/doc_src_sql-driver.qdoc 17 + + By default the Microsoft library is used on Windows, if you want to + force the use of the Sybase Open Client, you must define \c + Q_USE_SYBASE in \c{%QTDIR%\src\sql\drivers\tds\qsql_tds.cpp}. If you + are not using a Microsoft compiler, replace \c nmake with \c make in + the line above. + + \bold{Note:} This database plugin is not supported for Windows CE. + + \target QDB2 + \section2 QDB2 for IBM DB2 (Version 7.1 and Above) + + \section3 General Information about QDB2 + + The Qt DB2 plugin makes it possible to access IBM DB2 databases. It + has been tested with IBM DB2 v7.1 and 7.2. You must install the IBM + DB2 development client library, which contains the header and library + files necessary for compiling the QDB2 plugin. + + The QDB2 driver supports prepared queries, reading/writing of Unicode + strings and reading/writing of BLOBs. + + We suggest using a forward-only query when calling stored procedures + in DB2 (see QSqlQuery::setForwardOnly()). + + \section3 How to Build the QDB2 Plugin on Unix and Mac OS X + + \snippet doc/src/snippets/code/doc_src_sql-driver.qdoc 18 + + After installing Qt, as described in the \l{Installing Qt on X11 Platforms} document, + you also need to install the plugin in the standard location: + + \snippet doc/src/snippets/code/doc_src_sql-driver.qdoc 19 + + \section3 How to Build the QDB2 Plugin on Windows + + The DB2 header and include files should already be installed in the + right directories. You just have to build the plugin as follows: + + \snippet doc/src/snippets/code/doc_src_sql-driver.qdoc 20 + + If you are not using a Microsoft compiler, replace \c nmake + with \c make in the line above. + + \bold{Note:} This database plugin is not supported for Windows CE. + + \target QSQLITE2 + \section2 QSQLITE2 for SQLite Version 2 + + The Qt SQLite 2 plugin is offered for compatibility. Whenever + possible, use the \l{#QSQLITE}{version 3 plugin} instead. The + build instructions for version 3 apply to version 2 as well. + + \target QSQLITE + \section2 QSQLITE for SQLite (Version 3 and Above) + + \section3 General Information about QSQLITE + + The Qt SQLite plugin makes it possible to access SQLite + databases. SQLite is an in-process database, which means that it + is not necessary to have a database server. SQLite operates on a + single file, which must be set as the database name when opening + a connection. If the file does not exist, SQLite will try to + create it. SQLite also supports in-memory databases, simply pass + ":memory:" as the database name. + + SQLite has some restrictions regarding multiple users and + multiple transactions. If you try to read/write on a resource from different + transactions, your application might freeze until one transaction commits + or rolls back. The Qt SQLite driver will retry to write to a locked resource + until it runs into a timeout (see \c{QSQLITE_BUSY_TIMEOUT} + at QSqlDatabase::setConnectOptions()). + + In SQLite any column, with the exception of an INTEGER PRIMARY KEY column, + may be used to store any type of value. For instance, a column declared as + INTEGER may contain an integer value in one row and a text value in the + next. This is due to SQLite associating the type of a value with the value + itself rather than with the column it is stored in. A consequence of this + is that the type returned by QSqlField::type() only indicates the field's + recommended type. No assumption of the actual type should be made from + this and the type of the individual values should be checked. + + The driver is locked for updates while a select is executed. This + may cause problems when using QSqlTableModel because Qt's item views + fetch data as needed (with QSqlQuery::fetchMore() in the case of + QSqlTableModel). + + You can find information about SQLite on \l{http://www.sqlite.org}. + + \section3 How to Build the QSQLITE Plugin + + SQLite version 3 is included as a third-party library within Qt. + It can be built by passing the following parameters to the + configure script: \c{-plugin-sql-sqlite} (build as a plugin) or + \c{-qt-sql-sqlite} (linked directly into the Qt library). + + If you don't want to use the SQLite library included with Qt, you + can build it manually (replace \c $SQLITE by the directory where + SQLite resides): + + \snippet doc/src/snippets/code/doc_src_sql-driver.qdoc 21 + + After installing Qt, as described in the \l{Installing Qt on X11 Platforms} document, + you also need to install the plugin in the standard location: + + \snippet doc/src/snippets/code/doc_src_sql-driver.qdoc 22 + + On Windows: + + \snippet doc/src/snippets/code/doc_src_sql-driver.qdoc 23 + + \section3 QSQLITE File Format Compatibility + + SQLite minor releases sometimes break file format forward compatibility. + For example, SQLite 3.3 can read database files created with SQLite 3.2, + but databases created with SQLite 3.3 cannot be read by SQLite 3.2. + Please refer to the SQLite documentation and change logs for information about + file format compatibility between versions. + + Qt minor releases usually follow the SQLite minor releases, while Qt patch releases + follow SQLite patch releases. Patch releases are therefore both backward and forward + compatible. + + To force SQLite to use a specific file format, it is neccessary to build and + ship your own database plugin with your own SQLite library as illustrated above. + Some versions of SQLite can be forced to write a specific file format by setting + the \c{SQLITE_DEFAULT_FILE_FORMAT} define when building SQLite. + + \target QIBASE + \section2 QIBASE for Borland InterBase + + \section3 General Information about QIBASE + + The Qt InterBase plugin makes it possible to access the InterBase and + Firebird databases. InterBase can either be used as a client/server or + without a server in which case it operates on local files. The + database file must exist before a connection can be established. + + Note that InterBase requires you to specify the full path to the + database file, no matter whether it is stored locally or on another + server. + + \snippet doc/src/snippets/code/doc_src_sql-driver.qdoc 24 + + You need the InterBase/Firebird development headers and libraries + to build this plugin. + + Due to license incompatibilities with the GPL, users of the Qt Open Source + Edition are not allowed to link this plugin to the commercial editions of + InterBase. Please use Firebird or the free edition of InterBase. + + \section3 QIBASE Unicode Support and Text Encoding + + 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. + + \snippet doc/src/snippets/code/doc_src_sql-driver.qdoc 25 + + If Qt doesn't support the given text encoding the driver will issue a + warning message and connect to the database using UNICODE_FSS. + + Note that if the text encoding set when connecting to the database is + not the same as in the database, problems with transliteration might arise. + + \section3 QIBASE Stored procedures + + 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: + + \snippet doc/src/snippets/code/doc_src_sql-driver.qdoc 26 + + \section3 How to Build the QIBASE Plugin on Unix and Mac OS X + + The following assumes InterBase or Firebird is installed in + \c{/opt/interbase}: + + If you are using InterBase: + + \snippet doc/src/snippets/code/doc_src_sql-driver.qdoc 27 + + If you are using Firebird, the Firebird library has to be set explicitly: + + \snippet doc/src/snippets/code/doc_src_sql-driver.qdoc 28 + + \section3 How to Build the QIBASE Plugin on Windows + + The following assumes InterBase or Firebird is installed in + \c{C:\interbase}: + + If you are using InterBase: + + \snippet doc/src/snippets/code/doc_src_sql-driver.qdoc 29 + + If you are using Firebird, the Firebird library has to be set explicitely: + + \snippet doc/src/snippets/code/doc_src_sql-driver.qdoc 30 + + If you are not using a Microsoft compiler, replace \c nmake + with \c make in the line above. + + Note that \c{C:\interbase\bin} must be in the \c PATH. + + \bold{Note:} This database plugin is not supported for Windows CE. + + \target troubleshooting + \section1 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 distibution 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 \c{COFF2OMF.EXE} to convert libraries that have been + generated with Microsoft Visual C++. + + If the compilation of a plugin succeeds but it cannot be loaded, + make sure that the following requirements are met: + + \list + \i Ensure that you are using a shared Qt library; you cannot use the + plugins with a static build. + \i Ensure that the plugin is in the correct directory. You can use + QApplication::libraryPaths() to determine where Qt looks for plugins. + \i Ensure that the client libraries of the DBMS are available on the + system. On Unix, run the command \c{ldd} and pass the name of the + plugin as parameter, for example \c{ldd libqsqlmysql.so}. You will + get a warning if any of the client libraries couldn't be found. + On Windows, you can use Visual Studio's dependency walker. + \i Compile Qt with \c{QT_DEBUG_COMPONENT} defined to get very verbose + debug output when loading plugins. + \endlist + + Make sure you have followed the guide to \l{Deploying Plugins}. + If you experience plugin load problems and see output like this: + + \snippet doc/src/snippets/code/doc_src_sql-driver.qdoc 31 + + the problem is usually that the plugin had the wrong \l{Deploying + Plugins#The Build Key}{build key}. This might require removing an + entry from the \l{Deploying Plugins#The Plugin Cache} {plugin cache}. + + \target development + \section1 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. + + QSqlDriver is an abstract base class which defines the functionality + of a SQL database driver. This includes functions such as + QSqlDriver::open() and QSqlDriver::close(). QSqlDriver is responsible + for connecting to a database, establish the proper environment, etc. + In addition, QSqlDriver can create QSqlQuery objects appropriate for + the particular database API. QSqlDatabase forwards many of its + function calls directly to QSqlDriver which provides the concrete + implementation. + + QSqlResult is an abstract base class which defines the functionality + of a SQL database query. This includes statements such as \c{SELECT}, + \c{UPDATE}, and \c{ALTER} \c{TABLE}. QSqlResult contains functions + such as QSqlResult::next() and QSqlResult::value(). QSqlResult is + responsible for sending queries to the database, returning result + data, etc. QSqlQuery forwards many of its function calls directly to + QSqlResult which provides the concrete implementation. + + QSqlDriver and QSqlResult are closely connected. When implementing a + Qt SQL driver, both of these classes must to be subclassed and the + abstract virtual methods in each class must be implemented. + + To implement a Qt SQL driver as a plugin (so that it is + recognized and loaded by the Qt library at runtime), the driver + must use the Q_EXPORT_PLUGIN2() macro. Read \l{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 + \c{QTDIR/src/plugins/sqldrivers} and \c{QTDIR/src/sql/drivers}. + + The following code can be used as a skeleton for a SQL driver: + + \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 47 + \codeline + \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 48 +*/ diff --git a/doc/src/sql-programming/sql-programming.qdoc b/doc/src/sql-programming/sql-programming.qdoc new file mode 100644 index 0000000..7700a3d --- /dev/null +++ b/doc/src/sql-programming/sql-programming.qdoc @@ -0,0 +1,614 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the documentation of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain +** additional rights. These rights are described in the Nokia Qt LGPL +** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this +** package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 3.0 as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU General Public License version 3.0 requirements will be +** met: http://www.gnu.org/copyleft/gpl.html. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at http://qt.nokia.com/contact. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +/*! + \group database + \title Database Classes + + \brief Database related classes, e.g. for SQL databases. +*/ + +/*! + \page sql-programming.html + \title SQL Programming + + \brief Database integration for Qt applications. + + This overview assumes that you have at least a basic knowledge of + SQL. You should be able to understand simple \c SELECT, \c + INSERT, \c UPDATE, and \c DELETE statements. Although the \l + QSqlTableModel class provides an interface to database browsing + and editing that does not require a knowledge of SQL, a basic + understanding of SQL is highly recommended. A standard text + covering SQL databases is \e {An Introduction to Database Systems} + (7th Ed.) by C. J. Date, ISBN 0201385902. + + \section1 Topics: + + \list + \o \l{Database Classes} + \o \l{Connecting to Databases} + \list + \o \l{SQL Database Drivers} + \endlist + \o \l{Executing SQL Statements} + \list + \o \l{Recommended Use of Data Types in Databases} + \endlist + \o \l{Using the SQL Model Classes} + \o \l{Presenting Data in a Table View} + \o \l{Creating Data-Aware Forms} + \endlist + + \section1 Database Classes + + These classes provide access to SQL databases. + + \annotatedlist database + + The SQL classes are divided into three layers: + + \section2 Driver Layer + + This comprises the classes QSqlDriver, QSqlDriverCreator<T>, + QSqlDriverCreatorBase, QSqlDriverPlugin, and QSqlResult. + + This layer provides the low-level bridge between the specific databases + and the SQL API layer. See \l{SQL Database Drivers} for more information. + + \section2 SQL API Layer + + These classes provide access to databases. Connections + are made using the QSqlDatabase class. Database + interaction is achieved by using the QSqlQuery class. + In addition to QSqlDatabase and QSqlQuery, the SQL API + layer is supported by QSqlError, QSqlField, QSqlIndex, + and QSqlRecord. + + \section2 User Interface Layer + + These classes link the data from a database to data-aware widgets. + They include QSqlQueryModel, QSqlTableModel, and QSqlRelationalTableModel. + These classes are designed to work with Qt's + \l{Model/View Programming}{model/view framework}. + + Note that to use any of these classes, a QCoreApplication object + must have been instantiated first. +*/ + +/*! + \page sql-connecting.html + \title Connecting to Databases + + \contentspage SQL Programming + \nextpage Executing SQL Statements + + To access a database with QSqlQuery or QSqlQueryModel, create and + open one or more database connections. Database connections are + normally identified by connection name, \e{not} by database name. + You can have multiple connections to the same database. + QSqlDatabase also supports the concept of a \e{default} + connection, which is an unnamed connection. When calling QSqlQuery + or QSqlQueryModel member functions that take a connection name + argument, if you don't pass a connection name, the default + connection will be used. Creating a default connection is + convenient when your application only requires one database + connection. + + Note the difference between creating a connection and opening it. + Creating a connection involves creating an instance of class + QSqlDatabase. The connection is not usable until it is opened. The + following snippet shows how to create a \e{default} connection + and then open it: + + \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 26 + + The first line creates the connection object, and the last line + opens it for use. In between, we initialize some connection + information, including the \l{QSqlDatabase::setDatabaseName()} + {database name}, the \l{QSqlDatabase::setHostName()} {host name}, + the \l{QSqlDatabase::setUserName()} {user name}, and the + \l{QSqlDatabase::setPassword()} {password}. In this case, we are + connecting to the MySQL database \c{flightdb} on the host + \c{bigblue}. The \c{"QMYSQL"} argument to + \l{QSqlDatabase::addDatabase()} {addDatabase()} specifies the type + of database driver to use for the connection. The set of database + drivers included with Qt are shown in the table of \l{SQL Database + Drivers#Supported Databases} {supported database drivers}. + + The connection in the snippet will be the \e{default} connection, + because we don't pass the second argument to + \l{QSqlDatabase::addDatabase()} {addDatabase()}, which is the + connection name. For example, here we establish two MySQL database + connections named \c{"first"} and \c{"second"}: + + \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 27 + + After these connections have been initialized, \l{QSqlDatabase::} + {open()} for each one to establish the live connections. If the + \l{QSqlDatabase::} {open()} fails, it returns false. In that case, + call QSqlDatabase::lastError() to get error information. + + Once a connection is established, we can call the static function + QSqlDatabase::database() from anywhere with a connection name to + get a pointer to that database connection. If we don't pass a + connection name, it will return the default connection. For + example: + + \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 28 + \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 29 + \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 30 + + To remove a database connection, first close the database using + QSqlDatabase::close(), then remove it using the static method + QSqlDatabase::removeDatabase(). +*/ + +/*! + \page sql-sqlstatements.html + \title Executing SQL Statements + + \previouspage Connecting to Databases + \contentspage SQL Programming + \nextpage Using the SQL Model Classes + + + The QSqlQuery class provides an interface for executing SQL + statements and navigating through the result set of a query. + + The QSqlQueryModel and QSqlTableModel classes described in the + next section provide a higher-level interface for accessing + databases. If you are unfamiliar with SQL, you might want to skip + directly to the next section (\l{Using the SQL Model Classes}). + + \section2 Executing a Query + + To execute an SQL statement, simply create a QSqlQuery object and + call QSqlQuery::exec() like this: + + \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 31 + + The QSqlQuery constructor accepts an optional QSqlDatabase object + that specifies which database connection to use. In the example + above, we don't specify any connection, so the default connection + is used. + + If an error occurs, \l{QSqlQuery::exec()}{exec()} returns false. + The error is then available as QSqlQuery::lastError(). + + \section2 Navigating the Result Set + + QSqlQuery provides access to the result set one record at a time. + After the call to \l{QSqlQuery::exec()}{exec()}, QSqlQuery's + internal pointer is located one position \e{before} the first + record. We must call QSqlQuery::next() once to advance to the + first record, then \l{QSqlQuery::next()}{next()} again repeatedly + to access the other records, until it returns false. Here's a + typical loop that iterates over all the records in order: + + \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 32 + + The QSqlQuery::value() function returns the value of a field in + the current record. Fields are specified as zero-based indexes. + QSqlQuery::value() returns a QVariant, a type that can hold + various C++ and core Qt data types such as \c int, QString, and + QByteArray. The different database types are automatically mapped + into the closest Qt equivalent. In the code snippet, we call + QVariant::toString() and QVariant::toInt() to convert + variants to QString and \c int. + + For an overview of the recommended types used with Qt supported + Databases, please refer to \l{Recommended Use of Data Types in Databases}{this table}. + + You can iterate back and forth using QSqlQuery::next(), + QSqlQuery::previous(), QSqlQuery::first(), QSqlQuery::last(), and + QSqlQuery::seek(). The current row index is returned by + QSqlQuery::at(), and the total number of rows in the result set + is avaliable as QSqlQuery::size() for databases that support it. + + To determine whether a database driver supports a given feature, + use QSqlDriver::hasFeature(). In the following example, we call + QSqlQuery::size() to determine the size of a result set of + the underlying database supports that feature; otherwise, we + navigate to the last record and use the query's position to tell + us how many records there are. + + \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 33 + + If you iterate through a result set only using next() and seek() + with positive values, you can call + QSqlQuery::setForwardOnly(true) before calling exec(). This is an + easy optimization that will speed up the query significantly when + operating on large result sets. + + \section2 Inserting, Updating, and Deleting Records + + QSqlQuery can execute arbitrary SQL statements, not just + \c{SELECT}s. The following example inserts a record into a table + using \c{INSERT}: + + \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 34 + + If you want to insert many records at the same time, it is often + more efficient to separate the query from the actual values being + inserted. This can be done using placeholders. Qt supports two + placeholder syntaxes: named binding and positional binding. + Here's an example of named binding: + + \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 35 + + Here's an example of positional binding: + + \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 36 + + Both syntaxes work with all database drivers provided by Qt. If + the database supports the syntax natively, Qt simply forwards the + query to the DBMS; otherwise, Qt simulates the placeholder syntax + by preprocessing the query. The actual query that ends up being + executed by the DBMS is available as QSqlQuery::executedQuery(). + + When inserting multiple records, you only need to call + QSqlQuery::prepare() once. Then you call + \l{QSqlQuery::bindValue()}{bindValue()} or + \l{QSqlQuery::addBindValue()}{addBindValue()} followed by + \l{QSqlQuery::exec()}{exec()} as many times as necessary. + + Besides performance, one advantage of placeholders is that you + can easily specify arbitrary values without having to worry about + escaping special characters. + + Updating a record is similar to inserting it into a table: + + \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 37 + + You can also use named or positional binding to associate + parameters to actual values. + + Finally, here's an example of a \c DELETE statement: + + \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 38 + + \section2 Transactions + + If the underlying database engine supports transactions, + QSqlDriver::hasFeature(QSqlDriver::Transactions) will return + true. You can use QSqlDatabase::transaction() to initiate a + transaction, followed by the SQL commands you want to execute + within the context of the transaction, and then either + QSqlDatabase::commit() or QSqlDatabase::rollback(). When + using transactions you must start the transaction before you + create your query. + + Example: + + \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 39 + + Transactions can be used to ensure that a complex operation is + atomic (for example, looking up a foreign key and creating a + record), or to provide a means of canceling a complex change in + the middle. + + \omit + It would be useful to mention transactions, and the fact that + some databases don't support them. + \endomit +*/ + +/*! + \page sql-model.html + \title Using the SQL Model Classes + + \previouspage Executing SQL Statements + \contentspage SQL Programming + \nextpage Presenting Data in a Table View + + In addition to QSqlQuery, Qt offers three higher-level classes + for accessing databases. These classes are QSqlQueryModel, + QSqlTableModel, and QSqlRelationalTableModel. + + \table + \row \o QSqlQueryModel + \o A read-only model based on an arbitrary SQL query. + \row \o QSqlTableModel + \o A read-write model that works on a single table. + \row \o QSqlRelationalTableModel + \o A QSqlTableModel subclass with foreign key support. + \endtable + + These classes derive from QAbstractTableModel (which in turn + inherits from QAbstractItemModel) and make it easy to present + data from a database in an item view class such as QListView and + QTableView. This is explained in detail in the \l{Presenting Data + in a Table View} section. + + Another advantage of using these classes is that it can make your + code easier to adapt to other data sources. For example, if you + use QSqlTableModel and later decide to use XML files to store + data instead of a database, it is essentially just a matter of + replacing one data model with another. + + \section2 The SQL Query Model + + QSqlQueryModel offers a read-only model based on an SQL query. + + Example: + + \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 40 + + After setting the query using QSqlQueryModel::setQuery(), you can + use QSqlQueryModel::record(int) to access the individual records. + You can also use QSqlQueryModel::data() and any of the other + functions inherited from QAbstractItemModel. + + There's also a \l{QSqlQueryModel::setQuery()}{setQuery()} + overload that takes a QSqlQuery object and operates on its result + set. This enables you to use any features of QSqlQuery to set up + the query (e.g., prepared queries). + + \section2 The SQL Table Model + + QSqlTableModel offers a read-write model that works on a single + SQL table at a time. + + Example: + + \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 41 + + QSqlTableModel is a high-level alternative to QSqlQuery for + navigating and modifying individual SQL tables. It typically + results in less code and requires no knowledge of SQL syntax. + + Use QSqlTableModel::record() to retrieve a row in the table, and + QSqlTableModel::setRecord() to modify the row. For example, the + following code will increase every employee's salary by 10 per + cent: + + \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 42 + + You can also use QSqlTableModel::data() and + QSqlTableModel::setData(), which are inherited from + QAbstractItemModel, to access the data. For example, here's how + to update a record using + \l{QSqlTableModel::setData()}{setData()}: + + \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 43 + + Here's how to insert a row and populate it: + + \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 44 + + Here's how to delete five consecutive rows: + + \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 45 + \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 46 + + The first argument to QSqlTableModel::removeRows() is the index + of the first row to delete. + + When you're finished changing a record, you should always call + QSqlTableModel::submitAll() to ensure that the changes are + written to the database. + + When and whether you actually \e need to call submitAll() depends + on the table's \l{QSqlTableModel::editStrategy()}{edit strategy}. + The default strategy is QSqlTableModel::OnRowChange, which + specifies that pending changes are applied to the database when + the user selects a different row. Other strategies are + QSqlTableModel::OnManualSubmit (where all changes are cached in + the model until you call submitAll()) and + QSqlTableModel::OnFieldChange (where no changes are cached). + These are mostly useful when QSqlTableModel is used with a view. + + QSqlTableModel::OnFieldChange seems to deliver the promise that + you never need to call submitAll() explicitly. There are two + pitfalls, though: + + \list + \o Without any caching, performance may drop significantly. + \o If you modify a primary key, the record might slip through + your fingers while you are trying to populate it. + \endlist + + \section2 The SQL Relational Table Model + + QSqlRelationalTableModel extends QSqlTableModel to provide + support for foreign keys. A foreign key is a 1-to-1 mapping + between a field in one table and the primary key field of another + table. For example, if a \c book table has a field called \c + authorid that refers to the author table's \c id field, we say + that \c authorid is a foreign key. + + \table + \row \o \inlineimage noforeignkeys.png + \o \inlineimage foreignkeys.png + \endtable + + The screenshot on the left shows a plain QSqlTableModel in a + QTableView. Foreign keys (\c city and \c country) aren't resolved + to human-readable values. The screenshot on the right shows a + QSqlRelationalTableModel, with foreign keys resolved into + human-readable text strings. + + The following code snippet shows how the QSqlRelationalTableModel + was set up: + + \snippet examples/sql/relationaltablemodel/relationaltablemodel.cpp 0 + \codeline + \snippet examples/sql/relationaltablemodel/relationaltablemodel.cpp 1 + \snippet examples/sql/relationaltablemodel/relationaltablemodel.cpp 2 + + See the QSqlRelationalTableModel documentation for details. +*/ + +/*! + \page sql-presenting.html + \title Presenting Data in a Table View + + \previouspage Using the SQL Model Classes + \contentspage SQL Programming + \nextpage Creating Data-Aware Forms + + The QSqlQueryModel, QSqlTableModel, and QSqlRelationalTableModel + classes can be used as a data source for Qt's view classes such + as QListView, QTableView, and QTreeView. In practice, QTableView + is by far the most common choice, because an SQL result set is + essentially a two-dimensional data structure. + + \image relationaltable.png A table view displaying a QSqlTableModel + + The following example creates a view based on an SQL data model: + + \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 17 + \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 18 + \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 19 + + If the model is a read-write model (e.g., QSqlTableModel), the + view lets the user edit the fields. You can disable this by + calling + + \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 20 + + You can use the same model as a data source for multiple views. + If the user edits the model through one of the views, the other + views will reflect the changes immediately. The + \l{sql/tablemodel}{Table Model} example shows how it works. + + View classes display a header at the top to label the columns. To + change the header texts, call + \l{QAbstractItemModel::setHeaderData()}{setHeaderData()} on the + model. The header's labels default to the table's field names. + For example: + + \snippet examples/sql/relationaltablemodel/relationaltablemodel.cpp 3 + + QTableView also has a vertical header on the left with numbers + identifying the rows. If you insert rows programmatically using + QSqlTableModel::insertRows(), the new rows will be marked with an + asterisk (*) until they are submitted using + \l{QSqlTableModel::submitAll()}{submitAll()} or automatically + when the user moves to another record (assuming the + \l{QSqlTableModel::EditStrategy}{edit strategy} is + QSqlTableModel::OnRowChange). + + \image insertrowinmodelview.png Inserting a row in a model + + Likewise, if you remove rows using + \l{QSqlTableModel::removeRows()}{removeRows()}, the rows will be + marked with an exclamation mark (!) until the change is + submitted. + + The items in the view are rendered using a delegate. The default + delegate, QItemDelegate, handles the most common data types (\c + int, QString, QImage, etc.). The delegate is also responsible for + providing editor widgets (e.g., a combobox) when the user starts + editing an item in the view. You can create your own delegates by + subclassing QAbstractItemDelegate or QItemDelegate. See + \l{Model/View Programming} for more information. + + QSqlTableModel is optimized to operate on a single table at a + time. If you need a read-write model that operates on an + arbitrary result set, you can subclass QSqlQueryModel and + reimplement \l{QAbstractItemModel::flags()}{flags()} and + \l{QAbstractItemModel::setData()}{setData()} to make it + read-write. The following two functions make fields 1 and 2 of a + query model editable: + + \snippet examples/sql/querymodel/editablesqlmodel.cpp 0 + \codeline + \snippet examples/sql/querymodel/editablesqlmodel.cpp 1 + + The setFirstName() helper function is defined as follows: + + \snippet examples/sql/querymodel/editablesqlmodel.cpp 2 + + The setLastName() function is similar. See the + \l{sql/querymodel}{Query Model} example for the complete source code. + + Subclassing a model makes it possible to customize it in many + ways: You can provide tooltips for the items, change the + background color, provide calculated values, provide different + values for viewing and editing, handle null values specially, and + more. See \l{Model/View Programming} as well as the \l + QAbstractItemView reference documentation for details. + + If all you need is to resolve a foreign key to a more + human-friendly string, you can use QSqlRelationalTableModel. For + best results, you should also use QSqlRelationalDelegate, a + delegate that provides combobox editors for editing foreign keys. + + \image relationaltable.png Editing a foreign key in a relational table + + The \l{sql/relationaltablemodel}{Relational Table Model} example + illustrates how to use QSqlRelationalTableModel in conjunction with + QSqlRelationalDelegate to provide tables with foreign key + support. +*/ + +/*! + \page sql-forms.html + \title Creating Data-Aware Forms + + \previouspage Presenting Data in a Table View + \contentspage SQL Programming + + Using the SQL models described above, the contents of a database can + be presented to other model/view components. For some applications, + it is sufficient to present this data using a standard item view, + such as QTableView. However, users of record-based applications often + require a form-based user interface in which data from a specific + row or column in a database table is used to populate editor widgets + on a form. + + Such data-aware forms can be created with the QDataWidgetMapper class, + a generic model/view component that is used to map data from a model + to specific widgets in a user interface. + + QDataWidgetMapper operates on a specific database table, mapping items + in the table on a row-by-row or column-by-column basis. As a result, + using QDataWidgetMapper with a SQL model is as simple as using it with + any other table model. + + \image qdatawidgetmapper-simple.png + + The \l{demos/books}{Books} demonstration shows how information can + be presented for easy access by using QDataWidgetMapper and a set of + simple input widgets. +*/ |