1// Copyright (C) 2016 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only
6 \title Database Classes
8 \brief Database related classes, e.g. for SQL databases.
12 \page sql-programming.html
13 \title SQL Programming
14 \nextpage Connecting to Databases
16 \brief Database integration for Qt applications.
18 This overview assumes that you have at least a basic knowledge of
19 SQL. You should be able to understand simple \c SELECT, \c
20 INSERT, \c UPDATE, and \c DELETE statements. Although the \l
21 QSqlTableModel class provides an interface to database browsing
22 and editing that does not require a knowledge of SQL, a basic
23 understanding of SQL is highly recommended. A standard text
24 covering SQL databases is \e {An Introduction to Database Systems}
25 (7th Ed.) by C. J. Date, ISBN 0201385902.
30 \li \l{Database Classes}
31 \li \l{Connecting to Databases}
33 \li \l{SQL Database Drivers}
35 \li \l{Executing SQL Statements}
37 \li \l{Data Types for Qt-supported Database Systems}
39 \li \l{Using the SQL Model Classes}
40 \li \l{Presenting Data in a Table View}
41 \li \l{Creating Data-Aware Forms}
44 \section1 Database Classes
46 These classes provide access to SQL databases.
48 \annotatedlist database
50 The SQL classes are divided into three layers:
52 \section2 Driver Layer
54 This comprises the classes QSqlDriver, QSqlDriverCreator,
55 QSqlDriverCreatorBase, QSqlDriverPlugin, and QSqlResult.
57 This layer provides the low-level bridge between the specific databases
58 and the SQL API layer. See \l{SQL Database Drivers} for more information.
60 \section2 SQL API Layer
62 These classes provide access to databases. Connections
63 are made using the QSqlDatabase class. Database
64 interaction is achieved by using the QSqlQuery class.
65 In addition to QSqlDatabase and QSqlQuery, the SQL API
66 layer is supported by QSqlError, QSqlField, QSqlIndex,
69 \section2 User Interface Layer
71 These classes link the data from a database to data-aware widgets.
72 They include QSqlQueryModel, QSqlTableModel, and QSqlRelationalTableModel.
73 These classes are designed to work with Qt's
74 \l{Model/View Programming}{model/view framework}.
76 Note that a QCoreApplication object must be instantiated before
77 using any of these classes.
81 \page sql-connecting.html
82 \title Connecting to Databases
84 \previouspage SQL Programming
85 \nextpage Executing SQL Statements
87 To access a database with QSqlQuery or QSqlQueryModel, create and
88 open one or more database connections. Database connections are
89 normally identified by connection name, \e{not} by database name.
90 You can have multiple connections to the same database.
91 QSqlDatabase also supports the concept of a \e{default}
92 connection, which is an unnamed connection. When calling QSqlQuery
93 or QSqlQueryModel member functions that take a connection name
94 argument, if you don't pass a connection name, the default
95 connection will be used. Creating a default connection is
96 convenient when your application only requires one database
99 Note the difference between creating a connection and opening it.
100 Creating a connection involves creating an instance of class
101 QSqlDatabase. The connection is not usable until it is opened. The
102 following snippet shows how to create a \e{default} connection
105 \snippet sqldatabase/sqldatabase.cpp 26
107 The first line creates the connection object, and the last line
108 opens it for use. In between, we initialize some connection
109 information, including the \l{QSqlDatabase::setDatabaseName()}
110 {database name}, the \l{QSqlDatabase::setHostName()} {host name},
111 the \l{QSqlDatabase::setUserName()} {user name}, and the
112 \l{QSqlDatabase::setPassword()} {password}. In this case, we are
113 connecting to the MySQL database \c{flightdb} on the host
114 \c{bigblue}. The \c{"QMYSQL"} argument to
115 \l{QSqlDatabase::addDatabase()} {addDatabase()} specifies the type
116 of database driver to use for the connection. The set of database
117 drivers included with Qt are shown in the table of \l{SQL Database
118 Drivers#Supported Databases} {supported database drivers}.
120 The connection in the snippet will be the \e{default} connection,
121 because we don't pass the second argument to
122 \l{QSqlDatabase::addDatabase()} {addDatabase()}, which is the
123 connection name. For example, here we establish two MySQL database
124 connections named \c{"first"} and \c{"second"}:
126 \snippet sqldatabase/sqldatabase.cpp 27
128 After these connections have been initialized, \l{QSqlDatabase::}
129 {open()} for each one to establish the live connections. If the
130 \l{QSqlDatabase::} {open()} fails, it returns \c false. In that case,
131 call QSqlDatabase::lastError() to get error information.
133 Once a connection is established, we can call the static function
134 QSqlDatabase::database() from anywhere with a connection name to
135 get a pointer to that database connection. If we don't pass a
136 connection name, it will return the default connection. For
139 \snippet sqldatabase/sqldatabase.cpp 28
140 \snippet sqldatabase/sqldatabase.cpp 29
141 \snippet sqldatabase/sqldatabase.cpp 30
143 To remove a database connection, first close the database using
144 QSqlDatabase::close(), then remove it using the static method
145 QSqlDatabase::removeDatabase().
149 \page sql-sqlstatements.html
150 \title Executing SQL Statements
152 \previouspage Connecting to Databases
153 \nextpage Using the SQL Model Classes
156 The QSqlQuery class provides an interface for executing SQL
157 statements and navigating through the result set of a query.
159 The QSqlQueryModel and QSqlTableModel classes described in the
160 next section provide a higher-level interface for accessing
161 databases. If you are unfamiliar with SQL, you might want to skip
162 directly to the next section (\l{Using the SQL Model Classes}).
164 \section2 Executing a Query
166 To execute an SQL statement, simply create a QSqlQuery object and
167 call QSqlQuery::exec() like this:
169 \snippet sqldatabase/sqldatabase.cpp 31
171 The QSqlQuery constructor accepts an optional QSqlDatabase object
172 that specifies which database connection to use. In the example
173 above, we don't specify any connection, so the default connection
176 If an error occurs, \l{QSqlQuery::exec()}{exec()} returns \c false.
177 The error is then available as QSqlQuery::lastError().
179 \section2 Navigating the Result Set
181 QSqlQuery provides access to the result set one record at a time.
182 After the call to \l{QSqlQuery::exec()}{exec()}, QSqlQuery's
183 internal pointer is located one position \e{before} the first
184 record. We must call QSqlQuery::next() once to advance to the
185 first record, then \l{QSqlQuery::next()}{next()} again repeatedly
186 to access the other records, until it returns \c false. Here's a
187 typical loop that iterates over all the records in order:
189 \snippet sqldatabase/sqldatabase.cpp 32
191 The QSqlQuery::value() function returns the value of a field in
192 the current record. Fields are specified as zero-based indexes.
193 QSqlQuery::value() returns a QVariant, a type that can hold
194 various C++ and core Qt data types such as \c int, QString, and
195 QByteArray. The different database types are automatically mapped
196 into the closest Qt equivalent. In the code snippet, we call
197 QVariant::toString() and QVariant::toInt() to convert
198 variants to QString and \c int.
200 For an overview of the recommended types for use with Qt-supported
201 Databases, please refer to \l{Data Types for Qt-supported Database
202 Systems} {this table}.
204 You can navigate within the dataset using QSqlQuery::next(),
205 QSqlQuery::previous(), QSqlQuery::first(), QSqlQuery::last(), and
206 QSqlQuery::seek(). The current row index is returned by
207 QSqlQuery::at(), and the total number of rows in the result set
208 is available as QSqlQuery::size() for databases that support it.
210 To determine whether a database driver supports a given feature,
211 use QSqlDriver::hasFeature(). In the following example, we call
212 QSqlQuery::size() to determine the size of a result set of
213 the underlying database supports that feature; otherwise, we
214 navigate to the last record and use the query's position to tell
215 us how many records there are.
217 \snippet sqldatabase/sqldatabase.cpp 33
219 If you navigate within a result set, and use next() and seek()
220 only for browsing forward, you can call QSqlQuery::setForwardOnly(true)
221 before calling exec(). This is an easy optimization that will speed up
222 the query significantly when operating on large result sets.
224 \section2 Inserting, Updating, and Deleting Records
226 QSqlQuery can execute arbitrary SQL statements, not just
227 \c{SELECT}s. The following example inserts a record into a table
230 \snippet sqldatabase/sqldatabase.cpp 34
232 If you want to insert many records at the same time, it is often
233 more efficient to separate the query from the actual values being
234 inserted. This can be done using placeholders. Qt supports two
235 placeholder syntaxes: named binding and positional binding.
236 Here's an example of named binding:
238 \snippet sqldatabase/sqldatabase.cpp 35
240 Here's an example of positional binding:
242 \snippet sqldatabase/sqldatabase.cpp 36
244 Both syntaxes work with all database drivers provided by Qt. If
245 the database supports the syntax natively, Qt simply forwards the
246 query to the DBMS; otherwise, Qt simulates the placeholder syntax
247 by preprocessing the query. The actual query that ends up being
248 executed by the DBMS is available as QSqlQuery::executedQuery().
250 When inserting multiple records, you only need to call
251 QSqlQuery::prepare() once. Then you call
252 \l{QSqlQuery::bindValue()}{bindValue()} or
253 \l{QSqlQuery::addBindValue()}{addBindValue()} followed by
254 \l{QSqlQuery::exec()}{exec()} as many times as necessary.
256 Besides performance, one advantage of placeholders is that you
257 can easily specify arbitrary values without having to worry about
258 escaping special characters.
260 Updating a record is similar to inserting it into a table:
262 \snippet sqldatabase/sqldatabase.cpp 37
264 You can also use named or positional binding to associate
265 parameters to actual values.
267 Finally, here's an example of a \c DELETE statement:
269 \snippet sqldatabase/sqldatabase.cpp 38
271 \section2 Transactions
273 If the underlying database engine supports transactions,
274 QSqlDriver::hasFeature(QSqlDriver::Transactions) will return
275 true. You can use QSqlDatabase::transaction() to initiate a
276 transaction, followed by the SQL commands you want to execute
277 within the context of the transaction, and then either
278 QSqlDatabase::commit() or QSqlDatabase::rollback(). When
279 using transactions you must start the transaction before you
284 \snippet sqldatabase/sqldatabase.cpp 39
286 Transactions can be used to ensure that a complex operation is
287 atomic (for example, looking up a foreign key and creating a
288 record), or to provide a means of canceling a complex change in
292 It would be useful to mention transactions, and the fact that
293 some databases don't support them.
299 \title Using the SQL Model Classes
301 \previouspage Executing SQL Statements
302 \nextpage Presenting Data in a Table View
304 In addition to QSqlQuery, Qt offers three higher-level classes
305 for accessing databases. These classes are QSqlQueryModel,
306 QSqlTableModel, and QSqlRelationalTableModel.
309 \row \li QSqlQueryModel
310 \li A read-only model based on an arbitrary SQL query.
311 \row \li QSqlTableModel
312 \li A read-write model that works on a single table.
313 \row \li QSqlRelationalTableModel
314 \li A QSqlTableModel subclass with foreign key support.
317 These classes derive from QAbstractTableModel (which in turn
318 inherits from QAbstractItemModel) and make it easy to present
319 data from a database in an item view class such as QListView and
320 QTableView. This is explained in detail in the \l{Presenting Data
321 in a Table View} section.
323 Another advantage of using these classes is that it can make your
324 code easier to adapt to other data sources. For example, if you
325 use QSqlTableModel and later decide to use XML files to store
326 data instead of a database, it is essentially just a matter of
327 replacing one data model with another.
329 \section2 The SQL Query Model
331 QSqlQueryModel offers a read-only model based on an SQL query.
335 \snippet sqldatabase/sqldatabase.cpp 40
337 After setting the query using QSqlQueryModel::setQuery(), you can
338 use QSqlQueryModel::record(int) to access the individual records.
339 You can also use QSqlQueryModel::data() and any of the other
340 functions inherited from QAbstractItemModel.
342 There's also a \l{QSqlQueryModel::setQuery()}{setQuery()}
343 overload that takes a QSqlQuery object and operates on its result
344 set. This enables you to use any features of QSqlQuery to set up
345 the query (e.g., prepared queries).
347 \section2 The SQL Table Model
349 QSqlTableModel offers a read-write model that works on a single
354 \snippet sqldatabase/sqldatabase.cpp 41
356 QSqlTableModel is a high-level alternative to QSqlQuery for
357 navigating and modifying individual SQL tables. It typically
358 results in less code and requires no knowledge of SQL syntax.
360 Use QSqlTableModel::record() to retrieve a row in the table, and
361 QSqlTableModel::setRecord() to modify the row. For example, the
362 following code will increase every employee's salary by 10 per
365 \snippet sqldatabase/sqldatabase.cpp 42
367 You can also use QSqlTableModel::data() and
368 QSqlTableModel::setData(), which are inherited from
369 QAbstractItemModel, to access the data. For example, here's how
370 to update a record using
371 \l{QSqlTableModel::setData()}{setData()}:
373 \snippet sqldatabase/sqldatabase.cpp 43
375 Here's how to insert a row and populate it:
377 \snippet sqldatabase/sqldatabase.cpp 44
379 Here's how to delete five consecutive rows:
381 \snippet sqldatabase/sqldatabase.cpp 45
382 \snippet sqldatabase/sqldatabase.cpp 46
384 The first argument to QSqlTableModel::removeRows() is the index
385 of the first row to delete.
387 When you're finished changing a record, you should always call
388 QSqlTableModel::submitAll() to ensure that the changes are
389 written to the database.
391 When and whether you actually \e need to call submitAll() depends
392 on the table's \l{QSqlTableModel::editStrategy()}{edit strategy}.
393 The default strategy is QSqlTableModel::OnRowChange, which
394 specifies that pending changes are applied to the database when
395 the user selects a different row. Other strategies are
396 QSqlTableModel::OnManualSubmit (where all changes are cached in
397 the model until you call submitAll()) and
398 QSqlTableModel::OnFieldChange (where no changes are cached).
399 These are mostly useful when QSqlTableModel is used with a view.
401 QSqlTableModel::OnFieldChange seems to deliver the promise that
402 you never need to call submitAll() explicitly. There are two
406 \li Without any caching, performance may drop significantly.
407 \li If you modify a primary key, the record might slip through
408 your fingers while you are trying to populate it.
411 \section2 The SQL Relational Table Model
413 QSqlRelationalTableModel extends QSqlTableModel to provide
414 support for foreign keys. A foreign key is a 1-to-1 mapping
415 between a field in one table and the primary key field of another
416 table. For example, if a \c book table has a field called \c
417 authorid that refers to the author table's \c id field, we say
418 that \c authorid is a foreign key.
421 \row \li \inlineimage noforeignkeys.png
422 \li \inlineimage foreignkeys.png
425 The screenshot on the left shows a plain QSqlTableModel in a
426 QTableView. Foreign keys (\c city and \c country) aren't resolved
427 to human-readable values. The screenshot on the right shows a
428 QSqlRelationalTableModel, with foreign keys resolved into
429 human-readable text strings.
431 The following code snippet shows how the QSqlRelationalTableModel
434 \snippet relationaltablemodel/relationaltablemodel.cpp 0
436 \snippet relationaltablemodel/relationaltablemodel.cpp 1
437 \snippet relationaltablemodel/relationaltablemodel.cpp 2
439 See the QSqlRelationalTableModel documentation for details.
443 \page sql-presenting.html
444 \title Presenting Data in a Table View
446 \previouspage Using the SQL Model Classes
447 \nextpage Creating Data-Aware Forms
449 The QSqlQueryModel, QSqlTableModel, and QSqlRelationalTableModel
450 classes can be used as a data source for Qt's view classes such
451 as QListView, QTableView, and QTreeView. In practice, QTableView
452 is by far the most common choice, because an SQL result set is
453 essentially a two-dimensional data structure.
455 \image relationaltable.png A table view displaying a QSqlTableModel
457 The following example creates a view based on an SQL data model:
459 \snippet sqldatabase/sqldatabase_snippet.cpp 17
460 \snippet sqldatabase/sqldatabase_snippet.cpp 18
461 \snippet sqldatabase/sqldatabase_snippet.cpp 19
463 If the model is a read-write model (e.g., QSqlTableModel), the
464 view lets the user edit the fields. You can disable this by
467 \snippet sqldatabase/sqldatabase_snippet.cpp 20
469 You can use the same model as a data source for multiple views.
470 If the user edits the model through one of the views, the other
471 views will reflect the changes immediately. The
472 \l{tablemodel}{Table Model} example shows how it works.
474 View classes display a header at the top to label the columns. To
475 change the header texts, call
476 \l{QAbstractItemModel::setHeaderData()}{setHeaderData()} on the
477 model. The header's labels default to the table's field names.
480 \snippet relationaltablemodel/relationaltablemodel.cpp 3
482 QTableView also has a vertical header on the left with numbers
483 identifying the rows. If you insert rows programmatically using
484 QSqlTableModel::insertRows(), the new rows will be marked with an
485 asterisk (*) until they are submitted using
486 \l{QSqlTableModel::submitAll()}{submitAll()} or automatically
487 when the user moves to another record (assuming the
488 \l{QSqlTableModel::EditStrategy}{edit strategy} is
489 QSqlTableModel::OnRowChange).
491 \image insertrowinmodelview.png Inserting a row in a model
493 Likewise, if you remove rows using
494 \l{QSqlTableModel::removeRows()}{removeRows()}, the rows will be
495 marked with an exclamation mark (!) until the change is
498 The items in the view are rendered using a delegate. The default
499 delegate, QItemDelegate, handles the most common data types (\c
500 int, QString, QImage, etc.). The delegate is also responsible for
501 providing editor widgets (e.g., a combobox) when the user starts
502 editing an item in the view. You can create your own delegates by
503 subclassing QAbstractItemDelegate or QItemDelegate. See
504 \l{Model/View Programming} for more information.
506 QSqlTableModel is optimized to operate on a single table at a
507 time. If you need a read-write model that operates on an
508 arbitrary result set, you can subclass QSqlQueryModel and
509 reimplement \l{QAbstractItemModel::flags()}{flags()} and
510 \l{QAbstractItemModel::setData()}{setData()} to make it
511 read-write. The following two functions make fields 1 and 2 of a
512 query model editable:
514 \snippet querymodel/editablesqlmodel.cpp 0
516 \snippet querymodel/editablesqlmodel.cpp 1
518 The setFirstName() helper function is defined as follows:
520 \snippet querymodel/editablesqlmodel.cpp 2
522 The setLastName() function is similar. See the
523 \l{querymodel}{Query Model} example for the complete source code.
525 Subclassing a model makes it possible to customize it in many
526 ways: You can provide tooltips for the items, change the
527 background color, provide calculated values, provide different
528 values for viewing and editing, handle null values specially, and
529 more. See \l{Model/View Programming} as well as the \l
530 QAbstractItemView reference documentation for details.
532 If all you need is to resolve a foreign key to a more
533 human-friendly string, you can use QSqlRelationalTableModel. For
534 best results, you should also use QSqlRelationalDelegate, a
535 delegate that provides combobox editors for editing foreign keys.
537 \image relationaltable.png Editing a foreign key in a relational table
539 The \l{relationaltablemodel}{Relational Table Model} example
540 illustrates how to use QSqlRelationalTableModel in conjunction with
541 QSqlRelationalDelegate to provide tables with foreign key
547 \title Creating Data-Aware Forms
549 \previouspage Presenting Data in a Table View
551 Using the SQL models described above, the contents of a database can
552 be presented to other model/view components. For some applications,
553 it is sufficient to present this data using a standard item view,
554 such as QTableView. However, users of record-based applications often
555 require a form-based user interface in which data from a specific
556 row or column in a database table is used to populate editor widgets
559 Such data-aware forms can be created with the QDataWidgetMapper class,
560 a generic model/view component that is used to map data from a model
561 to specific widgets in a user interface.
563 QDataWidgetMapper operates on a specific database table, mapping items
564 in the table on a row-by-row or column-by-column basis. As a result,
565 using QDataWidgetMapper with an SQL model is as simple as using it with
566 any other table model.
568 \image qdatawidgetmapper-simple.png
570 The \l{books}{Books} example shows how information can
571 be presented for easy access by using QDataWidgetMapper and a set of
572 simple input widgets.