Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
sql-programming.qdoc
Go to the documentation of this file.
1
// Copyright (C) 2016 The Qt Company Ltd.
2
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only
3
4
/*!
5
\group database
6
\title Database Classes
7
8
\brief Database related classes, e.g. for SQL databases.
9
*/
10
11
/*!
12
\page sql-programming.html
13
\title SQL Programming
14
\nextpage Connecting to Databases
15
16
\brief Database integration for Qt applications.
17
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.
26
27
\section1 Topics:
28
29
\list
30
\li \l{Database Classes}
31
\li \l{Connecting to Databases}
32
\list
33
\li \l{SQL Database Drivers}
34
\endlist
35
\li \l{Executing SQL Statements}
36
\list
37
\li \l{Data Types for Qt-supported Database Systems}
38
\endlist
39
\li \l{Using the SQL Model Classes}
40
\li \l{Presenting Data in a Table View}
41
\li \l{Creating Data-Aware Forms}
42
\endlist
43
44
\section1 Database Classes
45
46
These classes provide access to SQL databases.
47
48
\annotatedlist database
49
50
The SQL classes are divided into three layers:
51
52
\section2 Driver Layer
53
54
This comprises the classes QSqlDriver, QSqlDriverCreator,
55
QSqlDriverCreatorBase, QSqlDriverPlugin, and QSqlResult.
56
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.
59
60
\section2 SQL API Layer
61
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,
67
and QSqlRecord.
68
69
\section2 User Interface Layer
70
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}.
75
76
Note that a QCoreApplication object must be instantiated before
77
using any of these classes.
78
*/
79
80
/*!
81
\page sql-connecting.html
82
\title Connecting to Databases
83
84
\previouspage SQL Programming
85
\nextpage Executing SQL Statements
86
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
97
connection.
98
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
103
and then open it:
104
105
\snippet sqldatabase/sqldatabase.cpp 26
106
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}.
119
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"}:
125
126
\snippet sqldatabase/sqldatabase.cpp 27
127
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.
132
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
137
example:
138
139
\snippet sqldatabase/sqldatabase.cpp 28
140
\snippet sqldatabase/sqldatabase.cpp 29
141
\snippet sqldatabase/sqldatabase.cpp 30
142
143
To remove a database connection, first close the database using
144
QSqlDatabase::close(), then remove it using the static method
145
QSqlDatabase::removeDatabase().
146
*/
147
148
/*!
149
\page sql-sqlstatements.html
150
\title Executing SQL Statements
151
152
\previouspage Connecting to Databases
153
\nextpage Using the SQL Model Classes
154
155
156
The QSqlQuery class provides an interface for executing SQL
157
statements and navigating through the result set of a query.
158
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}).
163
164
\section2 Executing a Query
165
166
To execute an SQL statement, simply create a QSqlQuery object and
167
call QSqlQuery::exec() like this:
168
169
\snippet sqldatabase/sqldatabase.cpp 31
170
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
174
is used.
175
176
If an error occurs, \l{QSqlQuery::exec()}{exec()} returns \c false.
177
The error is then available as QSqlQuery::lastError().
178
179
\section2 Navigating the Result Set
180
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:
188
189
\snippet sqldatabase/sqldatabase.cpp 32
190
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.
199
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}.
203
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.
209
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.
216
217
\snippet sqldatabase/sqldatabase.cpp 33
218
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.
223
224
\section2 Inserting, Updating, and Deleting Records
225
226
QSqlQuery can execute arbitrary SQL statements, not just
227
\c{SELECT}s. The following example inserts a record into a table
228
using \c{INSERT}:
229
230
\snippet sqldatabase/sqldatabase.cpp 34
231
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:
237
238
\snippet sqldatabase/sqldatabase.cpp 35
239
240
Here's an example of positional binding:
241
242
\snippet sqldatabase/sqldatabase.cpp 36
243
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().
249
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.
255
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.
259
260
Updating a record is similar to inserting it into a table:
261
262
\snippet sqldatabase/sqldatabase.cpp 37
263
264
You can also use named or positional binding to associate
265
parameters to actual values.
266
267
Finally, here's an example of a \c DELETE statement:
268
269
\snippet sqldatabase/sqldatabase.cpp 38
270
271
\section2 Transactions
272
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
280
create your query.
281
282
Example:
283
284
\snippet sqldatabase/sqldatabase.cpp 39
285
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
289
the middle.
290
291
\omit
292
It would be useful to mention transactions, and the fact that
293
some databases don't support them.
294
\endomit
295
*/
296
297
/*!
298
\page sql-model.html
299
\title Using the SQL Model Classes
300
301
\previouspage Executing SQL Statements
302
\nextpage Presenting Data in a Table View
303
304
In addition to QSqlQuery, Qt offers three higher-level classes
305
for accessing databases. These classes are QSqlQueryModel,
306
QSqlTableModel, and QSqlRelationalTableModel.
307
308
\table
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.
315
\endtable
316
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.
322
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.
328
329
\section2 The SQL Query Model
330
331
QSqlQueryModel offers a read-only model based on an SQL query.
332
333
Example:
334
335
\snippet sqldatabase/sqldatabase.cpp 40
336
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.
341
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).
346
347
\section2 The SQL Table Model
348
349
QSqlTableModel offers a read-write model that works on a single
350
SQL table at a time.
351
352
Example:
353
354
\snippet sqldatabase/sqldatabase.cpp 41
355
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.
359
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
363
cent:
364
365
\snippet sqldatabase/sqldatabase.cpp 42
366
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()}:
372
373
\snippet sqldatabase/sqldatabase.cpp 43
374
375
Here's how to insert a row and populate it:
376
377
\snippet sqldatabase/sqldatabase.cpp 44
378
379
Here's how to delete five consecutive rows:
380
381
\snippet sqldatabase/sqldatabase.cpp 45
382
\snippet sqldatabase/sqldatabase.cpp 46
383
384
The first argument to QSqlTableModel::removeRows() is the index
385
of the first row to delete.
386
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.
390
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.
400
401
QSqlTableModel::OnFieldChange seems to deliver the promise that
402
you never need to call submitAll() explicitly. There are two
403
pitfalls, though:
404
405
\list
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.
409
\endlist
410
411
\section2 The SQL Relational Table Model
412
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.
419
420
\table
421
\row \li \inlineimage noforeignkeys.png
422
{Table showing city and country as numeric foreign key values}
423
\li \inlineimage foreignkeys.png
424
{Table showing city and country resolved to text strings}
425
\endtable
426
427
The screenshot on the left shows a plain QSqlTableModel in a
428
QTableView. Foreign keys (\c city and \c country) aren't resolved
429
to human-readable values. The screenshot on the right shows a
430
QSqlRelationalTableModel, with foreign keys resolved into
431
human-readable text strings.
432
433
The following code snippet shows how the QSqlRelationalTableModel
434
was set up:
435
436
\snippet relationaltablemodel/relationaltablemodel.cpp 0
437
\codeline
438
\snippet relationaltablemodel/relationaltablemodel.cpp 1
439
\snippet relationaltablemodel/relationaltablemodel.cpp 2
440
441
See the QSqlRelationalTableModel documentation for details.
442
*/
443
444
/*!
445
\page sql-presenting.html
446
\title Presenting Data in a Table View
447
448
\previouspage Using the SQL Model Classes
449
\nextpage Creating Data-Aware Forms
450
451
The QSqlQueryModel, QSqlTableModel, and QSqlRelationalTableModel
452
classes can be used as a data source for Qt's view classes such
453
as QListView, QTableView, and QTreeView. In practice, QTableView
454
is by far the most common choice, because an SQL result set is
455
essentially a two-dimensional data structure.
456
457
\image relationaltable.png A table view displaying a QSqlTableModel
458
459
The following example creates a view based on an SQL data model:
460
461
\snippet sqldatabase/sqldatabase_snippet.cpp 17
462
\snippet sqldatabase/sqldatabase_snippet.cpp 18
463
\snippet sqldatabase/sqldatabase_snippet.cpp 19
464
465
If the model is a read-write model (e.g., QSqlTableModel), the
466
view lets the user edit the fields. You can disable this by
467
calling
468
469
\snippet sqldatabase/sqldatabase_snippet.cpp 20
470
471
You can use the same model as a data source for multiple views.
472
If the user edits the model through one of the views, the other
473
views will reflect the changes immediately. The
474
\l{tablemodel}{Table Model} example shows how it works.
475
476
View classes display a header at the top to label the columns. To
477
change the header texts, call
478
\l{QAbstractItemModel::setHeaderData()}{setHeaderData()} on the
479
model. The header's labels default to the table's field names.
480
For example:
481
482
\snippet relationaltablemodel/relationaltablemodel.cpp 3
483
484
QTableView also has a vertical header on the left with numbers
485
identifying the rows. If you insert rows programmatically using
486
QSqlTableModel::insertRows(), the new rows will be marked with an
487
asterisk (*) until they are submitted using
488
\l{QSqlTableModel::submitAll()}{submitAll()} or automatically
489
when the user moves to another record (assuming the
490
\l{QSqlTableModel::EditStrategy}{edit strategy} is
491
QSqlTableModel::OnRowChange).
492
493
\image insertrowinmodelview.png Inserting a row in a model
494
495
Likewise, if you remove rows using
496
\l{QSqlTableModel::removeRows()}{removeRows()}, the rows will be
497
marked with an exclamation mark (!) until the change is
498
submitted.
499
500
The items in the view are rendered using a delegate. The default
501
delegate, QStyledItemDelegate, handles the most common data types (\c
502
int, QString, QImage, etc.). The delegate is also responsible for
503
providing editor widgets (e.g., a combobox) when the user starts
504
editing an item in the view. You can create your own delegates by
505
subclassing QAbstractItemDelegate or QStyledItemDelegate. See
506
\l{Model/View Programming} for more information.
507
508
QSqlTableModel is optimized to operate on a single table at a
509
time. If you need a read-write model that operates on an
510
arbitrary result set, you can subclass QSqlQueryModel and
511
reimplement \l{QAbstractItemModel::flags()}{flags()} and
512
\l{QAbstractItemModel::setData()}{setData()} to make it
513
read-write. The following two functions make fields 1 and 2 of a
514
query model editable:
515
516
\snippet querymodel/editablesqlmodel.cpp 0
517
\codeline
518
\snippet querymodel/editablesqlmodel.cpp 1
519
520
The setFirstName() helper function is defined as follows:
521
522
\snippet querymodel/editablesqlmodel.cpp 2
523
524
The setLastName() function is similar. See the
525
\l{querymodel}{Query Model} example for the complete source code.
526
527
Subclassing a model makes it possible to customize it in many
528
ways: You can provide tooltips for the items, change the
529
background color, provide calculated values, provide different
530
values for viewing and editing, handle null values specially, and
531
more. See \l{Model/View Programming} as well as the \l
532
QAbstractItemView reference documentation for details.
533
534
If all you need is to resolve a foreign key to a more
535
human-friendly string, you can use QSqlRelationalTableModel. For
536
best results, you should also use QSqlRelationalDelegate, a
537
delegate that provides combobox editors for editing foreign keys.
538
539
\image relationaltable.png Editing a foreign key in a relational table
540
541
The \l{relationaltablemodel}{Relational Table Model} example
542
illustrates how to use QSqlRelationalTableModel in conjunction with
543
QSqlRelationalDelegate to provide tables with foreign key
544
support.
545
*/
546
547
/*!
548
\page sql-forms.html
549
\title Creating Data-Aware Forms
550
551
\previouspage Presenting Data in a Table View
552
553
Using the SQL models described above, the contents of a database can
554
be presented to other model/view components. For some applications,
555
it is sufficient to present this data using a standard item view,
556
such as QTableView. However, users of record-based applications often
557
require a form-based user interface in which data from a specific
558
row or column in a database table is used to populate editor widgets
559
on a form.
560
561
Such data-aware forms can be created with the QDataWidgetMapper class,
562
a generic model/view component that is used to map data from a model
563
to specific widgets in a user interface.
564
565
QDataWidgetMapper operates on a specific database table, mapping items
566
in the table on a row-by-row or column-by-column basis. As a result,
567
using QDataWidgetMapper with an SQL model is as simple as using it with
568
any other table model.
569
570
\image qdatawidgetmapper-simple.png {The table depicts the relationship between the different fields}
571
572
The \l{books}{Books} example shows how information can
573
be presented for easy access by using QDataWidgetMapper and a set of
574
simple input widgets.
575
*/
qtbase
src
sql
doc
src
sql-programming.qdoc
Generated on
for Qt by
1.16.1