source: trunk/doc/src/qtsql.qdoc@ 109

Last change on this file since 109 was 2, checked in by Dmitry A. Kuminov, 16 years ago

Initially imported qt-all-opensource-src-4.5.1 from Trolltech.

File size: 24.0 KB
Line 
1/****************************************************************************
2**
3** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
4** Contact: Qt Software Information ([email protected])
5**
6** This file is part of the documentation of the Qt Toolkit.
7**
8** $QT_BEGIN_LICENSE:LGPL$
9** Commercial Usage
10** Licensees holding valid Qt Commercial licenses may use this file in
11** accordance with the Qt Commercial License Agreement provided with the
12** Software or, alternatively, in accordance with the terms contained in
13** a written agreement between you and Nokia.
14**
15** GNU Lesser General Public License Usage
16** Alternatively, this file may be used under the terms of the GNU Lesser
17** General Public License version 2.1 as published by the Free Software
18** Foundation and appearing in the file LICENSE.LGPL included in the
19** packaging of this file. Please review the following information to
20** ensure the GNU Lesser General Public License version 2.1 requirements
21** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
22**
23** In addition, as a special exception, Nokia gives you certain
24** additional rights. These rights are described in the Nokia Qt LGPL
25** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
26** package.
27**
28** GNU General Public License Usage
29** Alternatively, this file may be used under the terms of the GNU
30** General Public License version 3.0 as published by the Free Software
31** Foundation and appearing in the file LICENSE.GPL included in the
32** packaging of this file. Please review the following information to
33** ensure the GNU General Public License version 3.0 requirements will be
34** met: http://www.gnu.org/copyleft/gpl.html.
35**
36** If you are unsure which license is appropriate for your use, please
37** contact the sales department at [email protected].
38** $QT_END_LICENSE$
39**
40****************************************************************************/
41
42/*!
43 \module QtSql
44 \title QtSql Module
45 \contentspage Qt's Modules
46 \previouspage QtScript
47 \nextpage QtSvg
48 \ingroup modules
49
50 \brief The QtSql module helps you provide seamless database
51 integration to your Qt applications.
52
53 The SQL classes are divided into three layers:
54
55 \table
56 \header \o Layer \o Description
57 \row \o \bold{Driver Layer}
58 \o This comprises the classes QSqlDriver,
59 QSqlDriverCreator<T>, QSqlDriverCreatorBase,
60 QSqlDriverPlugin, and QSqlResult. This layer provides the
61 low-level bridge between the specific databases and the
62 SQL API layer. See \l{SQL Database Drivers} for more
63 information.
64 \row \o \bold{SQL API Layer}
65 \o These classes provide access to databases. Connections
66 are made using the QSqlDatabase class. Database
67 interaction is achieved by using the QSqlQuery class.
68 In addition to QSqlDatabase and QSqlQuery, the SQL API
69 layer is supported by QSqlError, QSqlField, QSqlIndex,
70 and QSqlRecord.
71
72 \row \o \bold{User Interface Layer}
73 \o These classes link the data from a database to
74 data-aware widgets. They include QSqlQueryModel,
75 QSqlTableModel, and QSqlRelationalTableModel. These
76 classes are designed to work with Qt's model/view
77 framework.
78 \endtable
79
80 Note that to use any of these classes, a QCoreApplication object
81 must have been instantiated first. To include the definitions of
82 the module's classes, use the following directive:
83
84 \snippet doc/src/snippets/code/doc_src_qtsql.qdoc 0
85
86 To link against the module, add this line to your \l qmake \c
87 .pro file:
88
89 \snippet doc/src/snippets/code/doc_src_qtsql.qdoc 1
90
91 The QtSql module is part of the \l{Qt Full Framework Edition} and the
92 \l{Open Source Versions of Qt}.
93
94 This overview assumes that you have at least a basic knowledge of
95 SQL. You should be able to understand simple \c SELECT, \c
96 INSERT, \c UPDATE, and \c DELETE statements. Although the \l
97 QSqlTableModel class provides an interface to database browsing
98 and editing that does not require a knowledge of SQL, a basic
99 understanding of SQL is highly recommended. A standard text
100 covering SQL databases is \e {An Introduction to Database Systems}
101 (7th Ed.) by C. J. Date, ISBN 0201385902.
102
103 Topics:
104
105 \tableofcontents
106
107 \section1 Connecting to Databases
108
109 To access a database with QSqlQuery or QSqlQueryModel, create and
110 open one or more database connections. Database connections are
111 normally identified by connection name, \e{not} by database name.
112 You can have multiple connections to the same database.
113 QSqlDatabase also supports the concept of a \e{default}
114 connection, which is an unnamed connection. When calling QSqlQuery
115 or QSqlQueryModel member functions that take a connection name
116 argument, if you don't pass a connection name, the default
117 connection will be used. Creating a default connection is
118 convenient when your application only requires one database
119 connection.
120
121 Note the difference between creating a connection and opening it.
122 Creating a connection involves creating an instance of class
123 QSqlDatabase. The connection is not usable until it is opened. The
124 following snippet shows how to create a \e{default} connection
125 and then open it:
126
127 \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 26
128
129 The first line creates the connection object, and the last line
130 opens it for use. In between, we initialize some connection
131 information, including the \l{QSqlDatabase::setDatabaseName()}
132 {database name}, the \l{QSqlDatabase::setHostName()} {host name},
133 the \l{QSqlDatabase::setUserName()} {user name}, and the
134 \l{QSqlDatabase::setPassword()} {password}. In this case, we are
135 connecting to the MySQL database \c{flightdb} on the host
136 \c{bigblue}. The \c{"QMYSQL"} argument to
137 \l{QSqlDatabase::addDatabase()} {addDatabase()} specifies the type
138 of database driver to use for the connection. The set of database
139 drivers included with Qt are shown in the table of \l{SQL Database
140 Drivers#Supported Databases} {supported database drivers}.
141
142 The connection in the snippet will be the \e{default} connection,
143 because we don't pass the second argument to
144 \l{QSqlDatabase::addDatabase()} {addDatabase()}, which is the
145 connection name. For example, here we establish two MySQL database
146 connections named \c{"first"} and \c{"second"}:
147
148 \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 27
149
150 After these connections have been initialized, \l{QSqlDatabase::}
151 {open()} for each one to establish the live connections. If the
152 \l{QSqlDatabase::} {open()} fails, it returns false. In that case,
153 call QSqlDatabase::lastError() to get error information.
154
155 Once a connection is established, we can call the static function
156 QSqlDatabase::database() from anywhere with a connection name to
157 get a pointer to that database connection. If we don't pass a
158 connection name, it will return the default connection. For
159 example:
160
161 \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 28
162 \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 29
163 \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 30
164
165 To remove a database connection, first close the database using
166 QSqlDatabase::close(), then remove it using the static method
167 QSqlDatabase::removeDatabase().
168
169 \section1 Executing SQL Statements
170
171 The QSqlQuery class provides an interface for executing SQL
172 statements and navigating through the result set of a query.
173
174 The QSqlQueryModel and QSqlTableModel classes described in the
175 next section provide a higher-level interface for accessing
176 databases. If you are unfamiliar with SQL, you might want to skip
177 directly to the next section (\l{Using the SQL Model Classes}).
178
179 \section2 Executing a Query
180
181 To execute an SQL statement, simply create a QSqlQuery object and
182 call QSqlQuery::exec() like this:
183
184 \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 31
185
186 The QSqlQuery constructor accepts an optional QSqlDatabase object
187 that specifies which database connection to use. In the example
188 above, we don't specify any connection, so the default connection
189 is used.
190
191 If an error occurs, \l{QSqlQuery::exec()}{exec()} returns false.
192 The error is then available as QSqlQuery::lastError().
193
194 \section2 Navigating the Result Set
195
196 QSqlQuery provides access to the result set one record at a time.
197 After the call to \l{QSqlQuery::exec()}{exec()}, QSqlQuery's
198 internal pointer is located one position \e{before} the first
199 record. We must call QSqlQuery::next() once to advance to the
200 first record, then \l{QSqlQuery::next()}{next()} again repeatedly
201 to access the other records, until it returns false. Here's a
202 typical loop that iterates over all the records in order:
203
204 \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 32
205
206 The QSqlQuery::value() function returns the value of a field in
207 the current record. Fields are specified as zero-based indexes.
208 QSqlQuery::value() returns a QVariant, a type that can hold
209 various C++ and core Qt data types such as \c int, QString, and
210 QByteArray. The different database types are automatically mapped
211 into the closest Qt equivalent. In the code snippet, we call
212 QVariant::toString() and QVariant::toInt() to convert
213 variants to QString and \c int.
214
215 You can iterate back and forth using QSqlQuery::next(),
216 QSqlQuery::previous(), QSqlQuery::first(), QSqlQuery::last(), and
217 QSqlQuery::seek(). The current row index is returned by
218 QSqlQuery::at(), and the total number of rows in the result set
219 is avaliable as QSqlQuery::size() for databases that support it.
220
221 To determine whether a database driver supports a given feature,
222 use QSqlDriver::hasFeature(). In the following example, we call
223 QSqlQuery::size() to determine the size of a result set of
224 the underlying database supports that feature; otherwise, we
225 navigate to the last record and use the query's position to tell
226 us how many records there are.
227
228 \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 33
229
230 If you iterate through a result set only using next() and seek()
231 with positive values, you can call
232 QSqlQuery::setForwardOnly(true) before calling exec(). This is an
233 easy optimization that will speed up the query significantly when
234 operating on large result sets.
235
236 \section2 Inserting, Updating, and Deleting Records
237
238 QSqlQuery can execute arbitrary SQL statements, not just
239 \c{SELECT}s. The following example inserts a record into a table
240 using \c{INSERT}:
241
242 \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 34
243
244 If you want to insert many records at the same time, it is often
245 more efficient to separate the query from the actual values being
246 inserted. This can be done using placeholders. Qt supports two
247 placeholder syntaxes: named binding and positional binding.
248 Here's an example of named binding:
249
250 \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 35
251
252 Here's an example of positional binding:
253
254 \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 36
255
256 Both syntaxes work with all database drivers provided by Qt. If
257 the database supports the syntax natively, Qt simply forwards the
258 query to the DBMS; otherwise, Qt simulates the placeholder syntax
259 by preprocessing the query. The actual query that ends up being
260 executed by the DBMS is available as QSqlQuery::executedQuery().
261
262 When inserting multiple records, you only need to call
263 QSqlQuery::prepare() once. Then you call
264 \l{QSqlQuery::bindValue()}{bindValue()} or
265 \l{QSqlQuery::addBindValue()}{addBindValue()} followed by
266 \l{QSqlQuery::exec()}{exec()} as many times as necessary.
267
268 Besides performance, one advantage of placeholders is that you
269 can easily specify arbitrary values without having to worry about
270 escaping special characters.
271
272 Updating a record is similar to inserting it into a table:
273
274 \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 37
275
276 You can also use named or positional binding to associate
277 parameters to actual values.
278
279 Finally, here's an example of a \c DELETE statement:
280
281 \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 38
282
283 \section2 Transactions
284
285 If the underlying database engine supports transactions,
286 QSqlDriver::hasFeature(QSqlDriver::Transactions) will return
287 true. You can use QSqlDatabase::transaction() to initiate a
288 transaction, followed by the SQL commands you want to execute
289 within the context of the transaction, and then either
290 QSqlDatabase::commit() or QSqlDatabase::rollback(). When
291 using transactions you must start the transaction before you
292 create your query.
293
294 Example:
295
296 \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 39
297
298 Transactions can be used to ensure that a complex operation is
299 atomic (for example, looking up a foreign key and creating a
300 record), or to provide a means of canceling a complex change in
301 the middle.
302
303 \omit
304 It would be useful to mention transactions, and the fact that
305 some databases don't support them.
306 \endomit
307
308 \section1 Using the SQL Model Classes
309
310 In addition to QSqlQuery, Qt offers three higher-level classes
311 for accessing databases. These classes are QSqlQueryModel,
312 QSqlTableModel, and QSqlRelationalTableModel.
313
314 \table
315 \row \o QSqlQueryModel
316 \o A read-only model based on an arbitrary SQL query.
317 \row \o QSqlTableModel
318 \o A read-write model that works on a single table.
319 \row \o QSqlRelationalTableModel
320 \o A QSqlTableModel subclass with foreign key support.
321 \endtable
322
323 These classes derive from QAbstractTableModel (which in turn
324 inherits from QAbstractItemModel) and make it easy to present
325 data from a database in an item view class such as QListView and
326 QTableView. This is explained in detail in the \l{Presenting Data
327 in a Table View} section.
328
329 Another advantage of using these classes is that it can make your
330 code easier to adapt to other data sources. For example, if you
331 use QSqlTableModel and later decide to use XML files to store
332 data instead of a database, it is essentially just a matter of
333 replacing one data model with another.
334
335 \section2 The SQL Query Model
336
337 QSqlQueryModel offers a read-only model based on an SQL query.
338
339 Example:
340
341 \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 40
342
343 After setting the query using QSqlQueryModel::setQuery(), you can
344 use QSqlQueryModel::record(int) to access the individual records.
345 You can also use QSqlQueryModel::data() and any of the other
346 functions inherited from QAbstractItemModel.
347
348 There's also a \l{QSqlQueryModel::setQuery()}{setQuery()}
349 overload that takes a QSqlQuery object and operates on its result
350 set. This enables you to use any features of QSqlQuery to set up
351 the query (e.g., prepared queries).
352
353 \section2 The SQL Table Model
354
355 QSqlTableModel offers a read-write model that works on a single
356 SQL table at a time.
357
358 Example:
359
360 \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 41
361
362 QSqlTableModel is a high-level alternative to QSqlQuery for
363 navigating and modifying individual SQL tables. It typically
364 results in less code and requires no knowledge of SQL syntax.
365
366 Use QSqlTableModel::record() to retrieve a row in the table, and
367 QSqlTableModel::setRecord() to modify the row. For example, the
368 following code will increase every employee's salary by 10 per
369 cent:
370
371 \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 42
372
373 You can also use QSqlTableModel::data() and
374 QSqlTableModel::setData(), which are inherited from
375 QAbstractItemModel, to access the data. For example, here's how
376 to update a record using
377 \l{QSqlTableModel::setData()}{setData()}:
378
379 \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 43
380
381 Here's how to insert a row and populate it:
382
383 \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 44
384
385 Here's how to delete five consecutive rows:
386
387 \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 45
388 \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 46
389
390 The first argument to QSqlTableModel::removeRows() is the index
391 of the first row to delete.
392
393 When you're finished changing a record, you should always call
394 QSqlTableModel::submitAll() to ensure that the changes are
395 written to the database.
396
397 When and whether you actually \e need to call submitAll() depends
398 on the table's \l{QSqlTableModel::editStrategy()}{edit strategy}.
399 The default strategy is QSqlTableModel::OnRowChange, which
400 specifies that pending changes are applied to the database when
401 the user selects a different row. Other strategies are
402 QSqlTableModel::OnManualSubmit (where all changes are cached in
403 the model until you call submitAll()) and
404 QSqlTableModel::OnFieldChange (where no changes are cached).
405 These are mostly useful when QSqlTableModel is used with a view.
406
407 QSqlTableModel::OnFieldChange seems to deliver the promise that
408 you never need to call submitAll() explicitly. There are two
409 pitfalls, though:
410
411 \list
412 \o Without any caching, performance may drop significantly.
413 \o If you modify a primary key, the record might slip through
414 your fingers while you are trying to populate it.
415 \endlist
416
417 \section2 The SQL Relational Table Model
418
419 QSqlRelationalTableModel extends QSqlTableModel to provide
420 support for foreign keys. A foreign key is a 1-to-1 mapping
421 between a field in one table and the primary key field of another
422 table. For example, if a \c book table has a field called \c
423 authorid that refers to the author table's \c id field, we say
424 that \c authorid is a foreign key.
425
426 \table
427 \row \o \inlineimage noforeignkeys.png
428 \o \inlineimage foreignkeys.png
429 \endtable
430
431 The screenshot on the left shows a plain QSqlTableModel in a
432 QTableView. Foreign keys (\c city and \c country) aren't resolved
433 to human-readable values. The screenshot on the right shows a
434 QSqlRelationalTableModel, with foreign keys resolved into
435 human-readable text strings.
436
437 The following code snippet shows how the QSqlRelationalTableModel
438 was set up:
439
440 \snippet examples/sql/relationaltablemodel/relationaltablemodel.cpp 0
441 \codeline
442 \snippet examples/sql/relationaltablemodel/relationaltablemodel.cpp 1
443 \snippet examples/sql/relationaltablemodel/relationaltablemodel.cpp 2
444
445 See the QSqlRelationalTableModel documentation for details.
446
447 \section1 Presenting Data in a Table View
448
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.
454
455 \image relationaltable.png A table view displaying a QSqlTableModel
456
457 The following example creates a view based on an SQL data model:
458
459 \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 17
460 \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 18
461 \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 19
462
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
465 calling
466
467 \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 20
468
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{sql/tablemodel}{Table Model} example shows how it works.
473
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.
478 For example:
479
480 \snippet examples/sql/relationaltablemodel/relationaltablemodel.cpp 3
481
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).
490
491 \image insertrowinmodelview.png Inserting a row in a model
492
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
496 submitted.
497
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.
505
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:
513
514 \snippet examples/sql/querymodel/editablesqlmodel.cpp 0
515 \codeline
516 \snippet examples/sql/querymodel/editablesqlmodel.cpp 1
517
518 The setFirstName() helper function is defined as follows:
519
520 \snippet examples/sql/querymodel/editablesqlmodel.cpp 2
521
522 The setLastName() function is similar. See the
523 \l{sql/querymodel}{Query Model} example for the complete source code.
524
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.
531
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.
536
537 \image relationaltable.png Editing a foreign key in a relational table
538
539 The \l{sql/relationaltablemodel}{Relational Table Model} example
540 illustrates how to use QSqlRelationalTableModel in conjunction with
541 QSqlRelationalDelegate to provide tables with foreign key
542 support.
543
544 \section1 Creating Data-Aware Forms
545
546 Using the SQL models described above, the contents of a database can
547 be presented to other model/view components. For some applications,
548 it is sufficient to present this data using a standard item view,
549 such as QTableView. However, users of record-based applications often
550 require a form-based user interface in which data from a specific
551 row or column in a database table is used to populate editor widgets
552 on a form.
553
554 Such data-aware forms can be created with the QDataWidgetMapper class,
555 a generic model/view component that is used to map data from a model
556 to specific widgets in a user interface.
557
558 QDataWidgetMapper operates on a specific database table, mapping items
559 in the table on a row-by-row or column-by-column basis. As a result,
560 using QDataWidgetMapper with a SQL model is as simple as using it with
561 any other table model.
562
563 \image qdatawidgetmapper-simple.png
564
565 The \l{demos/books}{Books} demonstration shows how information can
566 be presented for easy access by using QDataWidgetMapper and a set of
567 simple input widgets.
568*/
Note: See TracBrowser for help on using the repository browser.