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