Chapter 18.  Database Programming

Table of Contents

18.1. QSqlDatabase: Connecting to SQL from Qt
18.2. Queries and Result Sets
18.3. Database Models
18.4. Review Questions

[ fromfile: database.xml id: database ]

Abstract

This chapter gives a general introduction to the capabilities of Qt's SQL classes, using Sqlite as an example back-end.

Qt provides a platform-neutral database interface similar to JDBC.[104] It requires a driver for each specific database that it can connect to. To build the driver against a specific database, the development header files of the database and also its libraries must be available. You can use Qt to connect to a variety of different SQL databases, including Oracle, PostgreSQL, and Sybase SQL. In the examples that follow, we have tested our code with MySQL and SQLite on Linux.

If you develop something new with QtSQL, we recommend using SQLite syntax because it:

  1. Is open source.

  2. Comes with Qt.

  3. Does not require building Qt from source, or building a plugin, or setting up a standalone server.

  4. Maps each database to a single file on disk.

  5. Supports a subset of SQL which is available on most other systems.

SQLite is an in-process, zero-configuration database library. It does not run as a separate server. For concurrency, reliability, higher performance, faster startup/shutdown, and smaller memory requirements for your application, it is recommended that you connect instead to an external database process such as MySQL. But SQLite is probably sufficient for simple labs and for learning SQL.

[Important] What About Other Drivers?

For more information, see the Qt SQL drivers documentation page.

[Important] What Drivers Are Already Supported?

To find out which drivers are available to the current version of Qt:

  1. Run $QTDIR/demos/sqlbrowser, and you can see a driver list in a combobox on the initial Connection settings dialog, as shown in Figure 18.1.

  2. Call QSqlDatabase::drivers() from code.

Figure 18.1.  Sql Browser Connection Settings Dialog

Sql Browser Connection Settings Dialog

[Tip] Object-Relational Mapping Layer

If you want to completely isolate yourself from SQL and map objects directly to persistent storage, you might be interested in Code Synthesis ODB, an open source object-relational mapping layer with support for Qt types.



[104] Java Database Connectivity API