1 /****************************************************************************
2 **
3 ** Copyright (C) 2016 The Qt Company Ltd.
4 ** Contact: https://www.qt.io/licensing/
5 **
6 ** This file is part of the QtSql module of the Qt Toolkit.
7 **
8 ** $QT_BEGIN_LICENSE:LGPL$
9 ** Commercial License Usage
10 ** Licensees holding valid commercial Qt licenses may use this file in
11 ** accordance with the commercial license agreement provided with the
12 ** Software or, alternatively, in accordance with the terms contained in
13 ** a written agreement between you and The Qt Company. For licensing terms
14 ** and conditions see https://www.qt.io/terms-conditions. For further
15 ** information use the contact form at https://www.qt.io/contact-us.
16 **
17 ** GNU Lesser General Public License Usage
18 ** Alternatively, this file may be used under the terms of the GNU Lesser
19 ** General Public License version 3 as published by the Free Software
20 ** Foundation and appearing in the file LICENSE.LGPL3 included in the
21 ** packaging of this file. Please review the following information to
22 ** ensure the GNU Lesser General Public License version 3 requirements
23 ** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
24 **
25 ** GNU General Public License Usage
26 ** Alternatively, this file may be used under the terms of the GNU
27 ** General Public License version 2.0 or (at your option) the GNU General
28 ** Public license version 3 or any later version approved by the KDE Free
29 ** Qt Foundation. The licenses are as published by the Free Software
30 ** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
31 ** included in the packaging of this file. Please review the following
32 ** information to ensure the GNU General Public License requirements will
33 ** be met: https://www.gnu.org/licenses/gpl-2.0.html and
34 ** https://www.gnu.org/licenses/gpl-3.0.html.
35 **
36 ** $QT_END_LICENSE$
37 **
38 ****************************************************************************/
39
40 #include "qsqlquery.h"
41
42 //#define QT_DEBUG_SQL
43
44 #include "qdebug.h"
45 #include "qelapsedtimer.h"
46 #include "qatomic.h"
47 #include "qsqlrecord.h"
48 #include "qsqlresult.h"
49 #include "qsqldriver.h"
50 #include "qsqldatabase.h"
51 #include "private/qsqlnulldriver_p.h"
52 #include "qvector.h"
53 #include "qmap.h"
54
55 QT_BEGIN_NAMESPACE
56
57 class QSqlQueryPrivate
58 {
59 public:
60 QSqlQueryPrivate(QSqlResult* result);
61 ~QSqlQueryPrivate();
62 QAtomicInt ref;
63 QSqlResult* sqlResult;
64
65 static QSqlQueryPrivate* shared_null();
66 };
67
68 Q_GLOBAL_STATIC_WITH_ARGS(QSqlQueryPrivate, nullQueryPrivate, (0))
Q_GLOBAL_STATIC(QSqlNullDriver,nullDriver)69 Q_GLOBAL_STATIC(QSqlNullDriver, nullDriver)
70 Q_GLOBAL_STATIC_WITH_ARGS(QSqlNullResult, nullResult, (nullDriver()))
71
72 QSqlQueryPrivate* QSqlQueryPrivate::shared_null()
73 {
74 QSqlQueryPrivate *null = nullQueryPrivate();
75 null->ref.ref();
76 return null;
77 }
78
79 /*!
80 \internal
81 */
QSqlQueryPrivate(QSqlResult * result)82 QSqlQueryPrivate::QSqlQueryPrivate(QSqlResult* result)
83 : ref(1), sqlResult(result)
84 {
85 if (!sqlResult)
86 sqlResult = nullResult();
87 }
88
~QSqlQueryPrivate()89 QSqlQueryPrivate::~QSqlQueryPrivate()
90 {
91 QSqlResult *nr = nullResult();
92 if (!nr || sqlResult == nr)
93 return;
94 delete sqlResult;
95 }
96
97 /*!
98 \class QSqlQuery
99 \brief The QSqlQuery class provides a means of executing and
100 manipulating SQL statements.
101
102 \ingroup database
103 \ingroup shared
104
105 \inmodule QtSql
106
107 QSqlQuery encapsulates the functionality involved in creating,
108 navigating and retrieving data from SQL queries which are
109 executed on a \l QSqlDatabase. It can be used to execute DML
110 (data manipulation language) statements, such as \c SELECT, \c
111 INSERT, \c UPDATE and \c DELETE, as well as DDL (data definition
112 language) statements, such as \c{CREATE} \c{TABLE}. It can also
113 be used to execute database-specific commands which are not
114 standard SQL (e.g. \c{SET DATESTYLE=ISO} for PostgreSQL).
115
116 Successfully executed SQL statements set the query's state to
117 active so that isActive() returns \c true. Otherwise the query's
118 state is set to inactive. In either case, when executing a new SQL
119 statement, the query is positioned on an invalid record. An active
120 query must be navigated to a valid record (so that isValid()
121 returns \c true) before values can be retrieved.
122
123 For some databases, if an active query that is a \c{SELECT}
124 statement exists when you call \l{QSqlDatabase::}{commit()} or
125 \l{QSqlDatabase::}{rollback()}, the commit or rollback will
126 fail. See isActive() for details.
127
128 \target QSqlQuery examples
129
130 Navigating records is performed with the following functions:
131
132 \list
133 \li next()
134 \li previous()
135 \li first()
136 \li last()
137 \li seek()
138 \endlist
139
140 These functions allow the programmer to move forward, backward
141 or arbitrarily through the records returned by the query. If you
142 only need to move forward through the results (e.g., by using
143 next()), you can use setForwardOnly(), which will save a
144 significant amount of memory overhead and improve performance on
145 some databases. Once an active query is positioned on a valid
146 record, data can be retrieved using value(). All data is
147 transferred from the SQL backend using QVariants.
148
149 For example:
150
151 \snippet sqldatabase/sqldatabase.cpp 7
152
153 To access the data returned by a query, use value(int). Each
154 field in the data returned by a \c SELECT statement is accessed
155 by passing the field's position in the statement, starting from
156 0. This makes using \c{SELECT *} queries inadvisable because the
157 order of the fields returned is indeterminate.
158
159 For the sake of efficiency, there are no functions to access a
160 field by name (unless you use prepared queries with names, as
161 explained below). To convert a field name into an index, use
162 record().\l{QSqlRecord::indexOf()}{indexOf()}, for example:
163
164 \snippet sqldatabase/sqldatabase.cpp 8
165
166 QSqlQuery supports prepared query execution and the binding of
167 parameter values to placeholders. Some databases don't support
168 these features, so for those, Qt emulates the required
169 functionality. For example, the Oracle and ODBC drivers have
170 proper prepared query support, and Qt makes use of it; but for
171 databases that don't have this support, Qt implements the feature
172 itself, e.g. by replacing placeholders with actual values when a
173 query is executed. Use numRowsAffected() to find out how many rows
174 were affected by a non-\c SELECT query, and size() to find how
175 many were retrieved by a \c SELECT.
176
177 Oracle databases identify placeholders by using a colon-name
178 syntax, e.g \c{:name}. ODBC simply uses \c ? characters. Qt
179 supports both syntaxes, with the restriction that you can't mix
180 them in the same query.
181
182 You can retrieve the values of all the fields in a single variable
183 (a map) using boundValues().
184
185 \note Not all SQL operations support binding values. Refer to your database
186 system's documentation to check their availability.
187
188 \section1 Approaches to Binding Values
189
190 Below we present the same example using each of the four
191 different binding approaches, as well as one example of binding
192 values to a stored procedure.
193
194 \b{Named binding using named placeholders:}
195
196 \snippet sqldatabase/sqldatabase.cpp 9
197
198 \b{Positional binding using named placeholders:}
199
200 \snippet sqldatabase/sqldatabase.cpp 10
201
202 \b{Binding values using positional placeholders (version 1):}
203
204 \snippet sqldatabase/sqldatabase.cpp 11
205
206 \b{Binding values using positional placeholders (version 2):}
207
208 \snippet sqldatabase/sqldatabase.cpp 12
209
210 \b{Binding values to a stored procedure:}
211
212 This code calls a stored procedure called \c AsciiToInt(), passing
213 it a character through its in parameter, and taking its result in
214 the out parameter.
215
216 \snippet sqldatabase/sqldatabase.cpp 13
217
218 Note that unbound parameters will retain their values.
219
220 Stored procedures that uses the return statement to return values,
221 or return multiple result sets, are not fully supported. For specific
222 details see \l{SQL Database Drivers}.
223
224 \warning You must load the SQL driver and open the connection before a
225 QSqlQuery is created. Also, the connection must remain open while the
226 query exists; otherwise, the behavior of QSqlQuery is undefined.
227
228 \sa QSqlDatabase, QSqlQueryModel, QSqlTableModel, QVariant
229 */
230
231 /*!
232 Constructs a QSqlQuery object which uses the QSqlResult \a result
233 to communicate with a database.
234 */
235
QSqlQuery(QSqlResult * result)236 QSqlQuery::QSqlQuery(QSqlResult *result)
237 {
238 d = new QSqlQueryPrivate(result);
239 }
240
241 /*!
242 Destroys the object and frees any allocated resources.
243 */
244
~QSqlQuery()245 QSqlQuery::~QSqlQuery()
246 {
247 if (!d->ref.deref())
248 delete d;
249 }
250
251 /*!
252 Constructs a copy of \a other.
253 */
254
QSqlQuery(const QSqlQuery & other)255 QSqlQuery::QSqlQuery(const QSqlQuery& other)
256 {
257 d = other.d;
258 d->ref.ref();
259 }
260
261 /*!
262 \internal
263 */
qInit(QSqlQuery * q,const QString & query,QSqlDatabase db)264 static void qInit(QSqlQuery *q, const QString& query, QSqlDatabase db)
265 {
266 QSqlDatabase database = db;
267 if (!database.isValid())
268 database = QSqlDatabase::database(QLatin1String(QSqlDatabase::defaultConnection), false);
269 if (database.isValid()) {
270 *q = QSqlQuery(database.driver()->createResult());
271 }
272 if (!query.isEmpty())
273 q->exec(query);
274 }
275
276 /*!
277 Constructs a QSqlQuery object using the SQL \a query and the
278 database \a db. If \a db is not specified, or is invalid, the application's
279 default database is used. If \a query is not an empty string, it
280 will be executed.
281
282 \sa QSqlDatabase
283 */
QSqlQuery(const QString & query,QSqlDatabase db)284 QSqlQuery::QSqlQuery(const QString& query, QSqlDatabase db)
285 {
286 d = QSqlQueryPrivate::shared_null();
287 qInit(this, query, db);
288 }
289
290 /*!
291 Constructs a QSqlQuery object using the database \a db.
292 If \a db is invalid, the application's default database will be used.
293
294 \sa QSqlDatabase
295 */
296
QSqlQuery(QSqlDatabase db)297 QSqlQuery::QSqlQuery(QSqlDatabase db)
298 {
299 d = QSqlQueryPrivate::shared_null();
300 qInit(this, QString(), db);
301 }
302
303
304 /*!
305 Assigns \a other to this object.
306 */
307
operator =(const QSqlQuery & other)308 QSqlQuery& QSqlQuery::operator=(const QSqlQuery& other)
309 {
310 qAtomicAssign(d, other.d);
311 return *this;
312 }
313
314 /*!
315 Returns \c true if the query is not \l{isActive()}{active},
316 the query is not positioned on a valid record,
317 there is no such \a field, or the \a field is null; otherwise \c false.
318 Note that for some drivers, isNull() will not return accurate
319 information until after an attempt is made to retrieve data.
320
321 \sa isActive(), isValid(), value()
322 */
323
isNull(int field) const324 bool QSqlQuery::isNull(int field) const
325 {
326 return !d->sqlResult->isActive()
327 || !d->sqlResult->isValid()
328 || d->sqlResult->isNull(field);
329 }
330
331 /*!
332 \overload
333
334 Returns \c true if there is no field with this \a name; otherwise
335 returns isNull(int index) for the corresponding field index.
336
337 This overload is less efficient than \l{QSqlQuery::}{isNull()}
338 */
339
isNull(const QString & name) const340 bool QSqlQuery::isNull(const QString &name) const
341 {
342 int index = d->sqlResult->record().indexOf(name);
343 if (index > -1)
344 return isNull(index);
345 qWarning("QSqlQuery::isNull: unknown field name '%s'", qPrintable(name));
346 return true;
347 }
348
349 /*!
350
351 Executes the SQL in \a query. Returns \c true and sets the query state
352 to \l{isActive()}{active} if the query was successful; otherwise
353 returns \c false. The \a query string must use syntax appropriate for
354 the SQL database being queried (for example, standard SQL).
355
356 After the query is executed, the query is positioned on an \e
357 invalid record and must be navigated to a valid record before data
358 values can be retrieved (for example, using next()).
359
360 Note that the last error for this query is reset when exec() is
361 called.
362
363 For SQLite, the query string can contain only one statement at a time.
364 If more than one statement is given, the function returns \c false.
365
366 Example:
367
368 \snippet sqldatabase/sqldatabase.cpp 34
369
370 \sa isActive(), isValid(), next(), previous(), first(), last(),
371 seek()
372 */
373
exec(const QString & query)374 bool QSqlQuery::exec(const QString& query)
375 {
376 #ifdef QT_DEBUG_SQL
377 QElapsedTimer t;
378 t.start();
379 #endif
380 if (d->ref.loadRelaxed() != 1) {
381 bool fo = isForwardOnly();
382 *this = QSqlQuery(driver()->createResult());
383 d->sqlResult->setNumericalPrecisionPolicy(d->sqlResult->numericalPrecisionPolicy());
384 setForwardOnly(fo);
385 } else {
386 d->sqlResult->clear();
387 d->sqlResult->setActive(false);
388 d->sqlResult->setLastError(QSqlError());
389 d->sqlResult->setAt(QSql::BeforeFirstRow);
390 d->sqlResult->setNumericalPrecisionPolicy(d->sqlResult->numericalPrecisionPolicy());
391 }
392 d->sqlResult->setQuery(query.trimmed());
393 if (!driver()->isOpen() || driver()->isOpenError()) {
394 qWarning("QSqlQuery::exec: database not open");
395 return false;
396 }
397 if (query.isEmpty()) {
398 qWarning("QSqlQuery::exec: empty query");
399 return false;
400 }
401
402 bool retval = d->sqlResult->reset(query);
403 #ifdef QT_DEBUG_SQL
404 qDebug().nospace() << "Executed query (" << t.elapsed() << "ms, " << d->sqlResult->size()
405 << " results, " << d->sqlResult->numRowsAffected()
406 << " affected): " << d->sqlResult->lastQuery();
407 #endif
408 return retval;
409 }
410
411 /*!
412 Returns the value of field \a index in the current record.
413
414 The fields are numbered from left to right using the text of the
415 \c SELECT statement, e.g. in
416
417 \snippet code/src_sql_kernel_qsqlquery_snippet.cpp 0
418
419 field 0 is \c forename and field 1 is \c
420 surname. Using \c{SELECT *} is not recommended because the order
421 of the fields in the query is undefined.
422
423 An invalid QVariant is returned if field \a index does not
424 exist, if the query is inactive, or if the query is positioned on
425 an invalid record.
426
427 \sa previous(), next(), first(), last(), seek(), isActive(), isValid()
428 */
429
value(int index) const430 QVariant QSqlQuery::value(int index) const
431 {
432 if (isActive() && isValid() && (index > -1))
433 return d->sqlResult->data(index);
434 qWarning("QSqlQuery::value: not positioned on a valid record");
435 return QVariant();
436 }
437
438 /*!
439 \overload
440
441 Returns the value of the field called \a name in the current record.
442 If field \a name does not exist an invalid variant is returned.
443
444 This overload is less efficient than \l{QSqlQuery::}{value()}
445 */
446
value(const QString & name) const447 QVariant QSqlQuery::value(const QString& name) const
448 {
449 int index = d->sqlResult->record().indexOf(name);
450 if (index > -1)
451 return value(index);
452 qWarning("QSqlQuery::value: unknown field name '%s'", qPrintable(name));
453 return QVariant();
454 }
455
456 /*!
457 Returns the current internal position of the query. The first
458 record is at position zero. If the position is invalid, the
459 function returns QSql::BeforeFirstRow or
460 QSql::AfterLastRow, which are special negative values.
461
462 \sa previous(), next(), first(), last(), seek(), isActive(), isValid()
463 */
464
at() const465 int QSqlQuery::at() const
466 {
467 return d->sqlResult->at();
468 }
469
470 /*!
471 Returns the text of the current query being used, or an empty
472 string if there is no current query text.
473
474 \sa executedQuery()
475 */
476
lastQuery() const477 QString QSqlQuery::lastQuery() const
478 {
479 return d->sqlResult->lastQuery();
480 }
481
482 /*!
483 Returns the database driver associated with the query.
484 */
485
driver() const486 const QSqlDriver *QSqlQuery::driver() const
487 {
488 return d->sqlResult->driver();
489 }
490
491 /*!
492 Returns the result associated with the query.
493 */
494
result() const495 const QSqlResult* QSqlQuery::result() const
496 {
497 return d->sqlResult;
498 }
499
500 /*!
501 Retrieves the record at position \a index, if available, and
502 positions the query on the retrieved record. The first record is at
503 position 0. Note that the query must be in an \l{isActive()}
504 {active} state and isSelect() must return true before calling this
505 function.
506
507 If \a relative is false (the default), the following rules apply:
508
509 \list
510
511 \li If \a index is negative, the result is positioned before the
512 first record and false is returned.
513
514 \li Otherwise, an attempt is made to move to the record at position
515 \a index. If the record at position \a index could not be retrieved,
516 the result is positioned after the last record and false is
517 returned. If the record is successfully retrieved, true is returned.
518
519 \endlist
520
521 If \a relative is true, the following rules apply:
522
523 \list
524
525 \li If the result is currently positioned before the first record and:
526 \list
527 \li \a index is negative or zero, there is no change, and false is
528 returned.
529 \li \a index is positive, an attempt is made to position the result
530 at absolute position \a index - 1, following the sames rule for non
531 relative seek, above.
532 \endlist
533
534 \li If the result is currently positioned after the last record and:
535 \list
536 \li \a index is positive or zero, there is no change, and false is
537 returned.
538 \li \a index is negative, an attempt is made to position the result
539 at \a index + 1 relative position from last record, following the
540 rule below.
541 \endlist
542
543 \li If the result is currently located somewhere in the middle, and
544 the relative offset \a index moves the result below zero, the result
545 is positioned before the first record and false is returned.
546
547 \li Otherwise, an attempt is made to move to the record \a index
548 records ahead of the current record (or \a index records behind the
549 current record if \a index is negative). If the record at offset \a
550 index could not be retrieved, the result is positioned after the
551 last record if \a index >= 0, (or before the first record if \a
552 index is negative), and false is returned. If the record is
553 successfully retrieved, true is returned.
554
555 \endlist
556
557 \sa next(), previous(), first(), last(), at(), isActive(), isValid()
558 */
seek(int index,bool relative)559 bool QSqlQuery::seek(int index, bool relative)
560 {
561 if (!isSelect() || !isActive())
562 return false;
563 int actualIdx;
564 if (!relative) { // arbitrary seek
565 if (index < 0) {
566 d->sqlResult->setAt(QSql::BeforeFirstRow);
567 return false;
568 }
569 actualIdx = index;
570 } else {
571 switch (at()) { // relative seek
572 case QSql::BeforeFirstRow:
573 if (index > 0)
574 actualIdx = index - 1;
575 else {
576 return false;
577 }
578 break;
579 case QSql::AfterLastRow:
580 if (index < 0) {
581 d->sqlResult->fetchLast();
582 actualIdx = at() + index + 1;
583 } else {
584 return false;
585 }
586 break;
587 default:
588 if ((at() + index) < 0) {
589 d->sqlResult->setAt(QSql::BeforeFirstRow);
590 return false;
591 }
592 actualIdx = at() + index;
593 break;
594 }
595 }
596 // let drivers optimize
597 if (isForwardOnly() && actualIdx < at()) {
598 qWarning("QSqlQuery::seek: cannot seek backwards in a forward only query");
599 return false;
600 }
601 if (actualIdx == (at() + 1) && at() != QSql::BeforeFirstRow) {
602 if (!d->sqlResult->fetchNext()) {
603 d->sqlResult->setAt(QSql::AfterLastRow);
604 return false;
605 }
606 return true;
607 }
608 if (actualIdx == (at() - 1)) {
609 if (!d->sqlResult->fetchPrevious()) {
610 d->sqlResult->setAt(QSql::BeforeFirstRow);
611 return false;
612 }
613 return true;
614 }
615 if (!d->sqlResult->fetch(actualIdx)) {
616 d->sqlResult->setAt(QSql::AfterLastRow);
617 return false;
618 }
619 return true;
620 }
621
622 /*!
623
624 Retrieves the next record in the result, if available, and positions
625 the query on the retrieved record. Note that the result must be in
626 the \l{isActive()}{active} state and isSelect() must return true
627 before calling this function or it will do nothing and return false.
628
629 The following rules apply:
630
631 \list
632
633 \li If the result is currently located before the first record,
634 e.g. immediately after a query is executed, an attempt is made to
635 retrieve the first record.
636
637 \li If the result is currently located after the last record, there
638 is no change and false is returned.
639
640 \li If the result is located somewhere in the middle, an attempt is
641 made to retrieve the next record.
642
643 \endlist
644
645 If the record could not be retrieved, the result is positioned after
646 the last record and false is returned. If the record is successfully
647 retrieved, true is returned.
648
649 \sa previous(), first(), last(), seek(), at(), isActive(), isValid()
650 */
next()651 bool QSqlQuery::next()
652 {
653 if (!isSelect() || !isActive())
654 return false;
655
656 switch (at()) {
657 case QSql::BeforeFirstRow:
658 return d->sqlResult->fetchFirst();
659 case QSql::AfterLastRow:
660 return false;
661 default:
662 if (!d->sqlResult->fetchNext()) {
663 d->sqlResult->setAt(QSql::AfterLastRow);
664 return false;
665 }
666 return true;
667 }
668 }
669
670 /*!
671
672 Retrieves the previous record in the result, if available, and
673 positions the query on the retrieved record. Note that the result
674 must be in the \l{isActive()}{active} state and isSelect() must
675 return true before calling this function or it will do nothing and
676 return false.
677
678 The following rules apply:
679
680 \list
681
682 \li If the result is currently located before the first record, there
683 is no change and false is returned.
684
685 \li If the result is currently located after the last record, an
686 attempt is made to retrieve the last record.
687
688 \li If the result is somewhere in the middle, an attempt is made to
689 retrieve the previous record.
690
691 \endlist
692
693 If the record could not be retrieved, the result is positioned
694 before the first record and false is returned. If the record is
695 successfully retrieved, true is returned.
696
697 \sa next(), first(), last(), seek(), at(), isActive(), isValid()
698 */
previous()699 bool QSqlQuery::previous()
700 {
701 if (!isSelect() || !isActive())
702 return false;
703 if (isForwardOnly()) {
704 qWarning("QSqlQuery::seek: cannot seek backwards in a forward only query");
705 return false;
706 }
707
708 switch (at()) {
709 case QSql::BeforeFirstRow:
710 return false;
711 case QSql::AfterLastRow:
712 return d->sqlResult->fetchLast();
713 default:
714 if (!d->sqlResult->fetchPrevious()) {
715 d->sqlResult->setAt(QSql::BeforeFirstRow);
716 return false;
717 }
718 return true;
719 }
720 }
721
722 /*!
723 Retrieves the first record in the result, if available, and
724 positions the query on the retrieved record. Note that the result
725 must be in the \l{isActive()}{active} state and isSelect() must
726 return true before calling this function or it will do nothing and
727 return false. Returns \c true if successful. If unsuccessful the query
728 position is set to an invalid position and false is returned.
729
730 \sa next(), previous(), last(), seek(), at(), isActive(), isValid()
731 */
first()732 bool QSqlQuery::first()
733 {
734 if (!isSelect() || !isActive())
735 return false;
736 if (isForwardOnly() && at() > QSql::BeforeFirstRow) {
737 qWarning("QSqlQuery::seek: cannot seek backwards in a forward only query");
738 return false;
739 }
740 return d->sqlResult->fetchFirst();
741 }
742
743 /*!
744
745 Retrieves the last record in the result, if available, and positions
746 the query on the retrieved record. Note that the result must be in
747 the \l{isActive()}{active} state and isSelect() must return true
748 before calling this function or it will do nothing and return false.
749 Returns \c true if successful. If unsuccessful the query position is
750 set to an invalid position and false is returned.
751
752 \sa next(), previous(), first(), seek(), at(), isActive(), isValid()
753 */
754
last()755 bool QSqlQuery::last()
756 {
757 if (!isSelect() || !isActive())
758 return false;
759 return d->sqlResult->fetchLast();
760 }
761
762 /*!
763 Returns the size of the result (number of rows returned), or -1 if
764 the size cannot be determined or if the database does not support
765 reporting information about query sizes. Note that for non-\c SELECT
766 statements (isSelect() returns \c false), size() will return -1. If the
767 query is not active (isActive() returns \c false), -1 is returned.
768
769 To determine the number of rows affected by a non-\c SELECT
770 statement, use numRowsAffected().
771
772 \sa isActive(), numRowsAffected(), QSqlDriver::hasFeature()
773 */
size() const774 int QSqlQuery::size() const
775 {
776 if (isActive() && d->sqlResult->driver()->hasFeature(QSqlDriver::QuerySize))
777 return d->sqlResult->size();
778 return -1;
779 }
780
781 /*!
782 Returns the number of rows affected by the result's SQL statement,
783 or -1 if it cannot be determined. Note that for \c SELECT
784 statements, the value is undefined; use size() instead. If the query
785 is not \l{isActive()}{active}, -1 is returned.
786
787 \sa size(), QSqlDriver::hasFeature()
788 */
789
numRowsAffected() const790 int QSqlQuery::numRowsAffected() const
791 {
792 if (isActive())
793 return d->sqlResult->numRowsAffected();
794 return -1;
795 }
796
797 /*!
798 Returns error information about the last error (if any) that
799 occurred with this query.
800
801 \sa QSqlError, QSqlDatabase::lastError()
802 */
803
lastError() const804 QSqlError QSqlQuery::lastError() const
805 {
806 return d->sqlResult->lastError();
807 }
808
809 /*!
810 Returns \c true if the query is currently positioned on a valid
811 record; otherwise returns \c false.
812 */
813
isValid() const814 bool QSqlQuery::isValid() const
815 {
816 return d->sqlResult->isValid();
817 }
818
819 /*!
820
821 Returns \c true if the query is \e{active}. An active QSqlQuery is one
822 that has been \l{QSqlQuery::exec()} {exec()'d} successfully but not
823 yet finished with. When you are finished with an active query, you
824 can make the query inactive by calling finish() or clear(), or
825 you can delete the QSqlQuery instance.
826
827 \note Of particular interest is an active query that is a \c{SELECT}
828 statement. For some databases that support transactions, an active
829 query that is a \c{SELECT} statement can cause a \l{QSqlDatabase::}
830 {commit()} or a \l{QSqlDatabase::} {rollback()} to fail, so before
831 committing or rolling back, you should make your active \c{SELECT}
832 statement query inactive using one of the ways listed above.
833
834 \sa isSelect()
835 */
isActive() const836 bool QSqlQuery::isActive() const
837 {
838 return d->sqlResult->isActive();
839 }
840
841 /*!
842 Returns \c true if the current query is a \c SELECT statement;
843 otherwise returns \c false.
844 */
845
isSelect() const846 bool QSqlQuery::isSelect() const
847 {
848 return d->sqlResult->isSelect();
849 }
850
851 /*!
852 Returns \c true if you can only scroll forward through a result set;
853 otherwise returns \c false.
854
855 \sa setForwardOnly(), next()
856 */
isForwardOnly() const857 bool QSqlQuery::isForwardOnly() const
858 {
859 return d->sqlResult->isForwardOnly();
860 }
861
862 /*!
863 Sets forward only mode to \a forward. If \a forward is true, only
864 next() and seek() with positive values, are allowed for navigating
865 the results.
866
867 Forward only mode can be (depending on the driver) more memory
868 efficient since results do not need to be cached. It will also
869 improve performance on some databases. For this to be true, you must
870 call \c setForwardOnly() before the query is prepared or executed.
871 Note that the constructor that takes a query and a database may
872 execute the query.
873
874 Forward only mode is off by default.
875
876 Setting forward only to false is a suggestion to the database engine,
877 which has the final say on whether a result set is forward only or
878 scrollable. isForwardOnly() will always return the correct status of
879 the result set.
880
881 \note Calling setForwardOnly after execution of the query will result
882 in unexpected results at best, and crashes at worst.
883
884 \note To make sure the forward-only query completed successfully,
885 the application should check lastError() for an error not only after
886 executing the query, but also after navigating the query results.
887
888 \warning PostgreSQL: While navigating the query results in forward-only
889 mode, do not execute any other SQL command on the same database
890 connection. This will cause the query results to be lost.
891
892 \sa isForwardOnly(), next(), seek(), QSqlResult::setForwardOnly()
893 */
setForwardOnly(bool forward)894 void QSqlQuery::setForwardOnly(bool forward)
895 {
896 d->sqlResult->setForwardOnly(forward);
897 }
898
899 /*!
900 Returns a QSqlRecord containing the field information for the
901 current query. If the query points to a valid row (isValid() returns
902 true), the record is populated with the row's values. An empty
903 record is returned when there is no active query (isActive() returns
904 false).
905
906 To retrieve values from a query, value() should be used since
907 its index-based lookup is faster.
908
909 In the following example, a \c{SELECT * FROM} query is executed.
910 Since the order of the columns is not defined, QSqlRecord::indexOf()
911 is used to obtain the index of a column.
912
913 \snippet code/src_sql_kernel_qsqlquery.cpp 1
914
915 \sa value()
916 */
record() const917 QSqlRecord QSqlQuery::record() const
918 {
919 QSqlRecord rec = d->sqlResult->record();
920
921 if (isValid()) {
922 for (int i = 0; i < rec.count(); ++i)
923 rec.setValue(i, value(i));
924 }
925 return rec;
926 }
927
928 /*!
929 Clears the result set and releases any resources held by the
930 query. Sets the query state to inactive. You should rarely if ever
931 need to call this function.
932 */
clear()933 void QSqlQuery::clear()
934 {
935 *this = QSqlQuery(driver()->createResult());
936 }
937
938 /*!
939 Prepares the SQL query \a query for execution. Returns \c true if the
940 query is prepared successfully; otherwise returns \c false.
941
942 The query may contain placeholders for binding values. Both Oracle
943 style colon-name (e.g., \c{:surname}), and ODBC style (\c{?})
944 placeholders are supported; but they cannot be mixed in the same
945 query. See the \l{QSqlQuery examples}{Detailed Description} for
946 examples.
947
948 Portability notes: Some databases choose to delay preparing a query
949 until it is executed the first time. In this case, preparing a
950 syntactically wrong query succeeds, but every consecutive exec()
951 will fail.
952 When the database does not support named placeholders directly,
953 the placeholder can only contain characters in the range [a-zA-Z0-9_].
954
955 For SQLite, the query string can contain only one statement at a time.
956 If more than one statement is given, the function returns \c false.
957
958 Example:
959
960 \snippet sqldatabase/sqldatabase.cpp 9
961
962 \sa exec(), bindValue(), addBindValue()
963 */
prepare(const QString & query)964 bool QSqlQuery::prepare(const QString& query)
965 {
966 if (d->ref.loadRelaxed() != 1) {
967 bool fo = isForwardOnly();
968 *this = QSqlQuery(driver()->createResult());
969 setForwardOnly(fo);
970 d->sqlResult->setNumericalPrecisionPolicy(d->sqlResult->numericalPrecisionPolicy());
971 } else {
972 d->sqlResult->setActive(false);
973 d->sqlResult->setLastError(QSqlError());
974 d->sqlResult->setAt(QSql::BeforeFirstRow);
975 d->sqlResult->setNumericalPrecisionPolicy(d->sqlResult->numericalPrecisionPolicy());
976 }
977 if (!driver()) {
978 qWarning("QSqlQuery::prepare: no driver");
979 return false;
980 }
981 if (!driver()->isOpen() || driver()->isOpenError()) {
982 qWarning("QSqlQuery::prepare: database not open");
983 return false;
984 }
985 if (query.isEmpty()) {
986 qWarning("QSqlQuery::prepare: empty query");
987 return false;
988 }
989 #ifdef QT_DEBUG_SQL
990 qDebug("\n QSqlQuery::prepare: %s", query.toLocal8Bit().constData());
991 #endif
992 return d->sqlResult->savePrepare(query);
993 }
994
995 /*!
996 Executes a previously prepared SQL query. Returns \c true if the query
997 executed successfully; otherwise returns \c false.
998
999 Note that the last error for this query is reset when exec() is
1000 called.
1001
1002 \sa prepare(), bindValue(), addBindValue(), boundValue(), boundValues()
1003 */
exec()1004 bool QSqlQuery::exec()
1005 {
1006 #ifdef QT_DEBUG_SQL
1007 QElapsedTimer t;
1008 t.start();
1009 #endif
1010 d->sqlResult->resetBindCount();
1011
1012 if (d->sqlResult->lastError().isValid())
1013 d->sqlResult->setLastError(QSqlError());
1014
1015 bool retval = d->sqlResult->exec();
1016 #ifdef QT_DEBUG_SQL
1017 qDebug().nospace() << "Executed prepared query (" << t.elapsed() << "ms, "
1018 << d->sqlResult->size() << " results, " << d->sqlResult->numRowsAffected()
1019 << " affected): " << d->sqlResult->lastQuery();
1020 #endif
1021 return retval;
1022 }
1023
1024 /*! \enum QSqlQuery::BatchExecutionMode
1025
1026 \value ValuesAsRows - Updates multiple rows. Treats every entry in a QVariantList as a value for updating the next row.
1027 \value ValuesAsColumns - Updates a single row. Treats every entry in a QVariantList as a single value of an array type.
1028 */
1029
1030 /*!
1031 \since 4.2
1032
1033 Executes a previously prepared SQL query in a batch. All the bound
1034 parameters have to be lists of variants. If the database doesn't
1035 support batch executions, the driver will simulate it using
1036 conventional exec() calls.
1037
1038 Returns \c true if the query is executed successfully; otherwise
1039 returns \c false.
1040
1041 Example:
1042
1043 \snippet code/src_sql_kernel_qsqlquery.cpp 2
1044
1045 The example above inserts four new rows into \c myTable:
1046
1047 \snippet code/src_sql_kernel_qsqlquery_snippet.cpp 3
1048
1049 To bind NULL values, a null QVariant of the relevant type has to be
1050 added to the bound QVariantList; for example, \c
1051 {QVariant(QVariant::String)} should be used if you are using
1052 strings.
1053
1054 \note Every bound QVariantList must contain the same amount of
1055 variants.
1056
1057 \note The type of the QVariants in a list must not change. For
1058 example, you cannot mix integer and string variants within a
1059 QVariantList.
1060
1061 The \a mode parameter indicates how the bound QVariantList will be
1062 interpreted. If \a mode is \c ValuesAsRows, every variant within
1063 the QVariantList will be interpreted as a value for a new row. \c
1064 ValuesAsColumns is a special case for the Oracle driver. In this
1065 mode, every entry within a QVariantList will be interpreted as
1066 array-value for an IN or OUT value within a stored procedure. Note
1067 that this will only work if the IN or OUT value is a table-type
1068 consisting of only one column of a basic type, for example \c{TYPE
1069 myType IS TABLE OF VARCHAR(64) INDEX BY BINARY_INTEGER;}
1070
1071 \sa prepare(), bindValue(), addBindValue()
1072 */
execBatch(BatchExecutionMode mode)1073 bool QSqlQuery::execBatch(BatchExecutionMode mode)
1074 {
1075 d->sqlResult->resetBindCount();
1076 return d->sqlResult->execBatch(mode == ValuesAsColumns);
1077 }
1078
1079 /*!
1080 Set the placeholder \a placeholder to be bound to value \a val in
1081 the prepared statement. Note that the placeholder mark (e.g \c{:})
1082 must be included when specifying the placeholder name. If \a
1083 paramType is QSql::Out or QSql::InOut, the placeholder will be
1084 overwritten with data from the database after the exec() call.
1085 In this case, sufficient space must be pre-allocated to store
1086 the result into.
1087
1088 To bind a NULL value, use a null QVariant; for example, use
1089 \c {QVariant(QVariant::String)} if you are binding a string.
1090
1091 \sa addBindValue(), prepare(), exec(), boundValue(), boundValues()
1092 */
bindValue(const QString & placeholder,const QVariant & val,QSql::ParamType paramType)1093 void QSqlQuery::bindValue(const QString& placeholder, const QVariant& val,
1094 QSql::ParamType paramType
1095 )
1096 {
1097 d->sqlResult->bindValue(placeholder, val, paramType);
1098 }
1099
1100 /*!
1101 Set the placeholder in position \a pos to be bound to value \a val
1102 in the prepared statement. Field numbering starts at 0. If \a
1103 paramType is QSql::Out or QSql::InOut, the placeholder will be
1104 overwritten with data from the database after the exec() call.
1105 */
bindValue(int pos,const QVariant & val,QSql::ParamType paramType)1106 void QSqlQuery::bindValue(int pos, const QVariant& val, QSql::ParamType paramType)
1107 {
1108 d->sqlResult->bindValue(pos, val, paramType);
1109 }
1110
1111 /*!
1112 Adds the value \a val to the list of values when using positional
1113 value binding. The order of the addBindValue() calls determines
1114 which placeholder a value will be bound to in the prepared query.
1115 If \a paramType is QSql::Out or QSql::InOut, the placeholder will be
1116 overwritten with data from the database after the exec() call.
1117
1118 To bind a NULL value, use a null QVariant; for example, use \c
1119 {QVariant(QVariant::String)} if you are binding a string.
1120
1121 \sa bindValue(), prepare(), exec(), boundValue(), boundValues()
1122 */
addBindValue(const QVariant & val,QSql::ParamType paramType)1123 void QSqlQuery::addBindValue(const QVariant& val, QSql::ParamType paramType)
1124 {
1125 d->sqlResult->addBindValue(val, paramType);
1126 }
1127
1128 /*!
1129 Returns the value for the \a placeholder.
1130
1131 \sa boundValues(), bindValue(), addBindValue()
1132 */
boundValue(const QString & placeholder) const1133 QVariant QSqlQuery::boundValue(const QString& placeholder) const
1134 {
1135 return d->sqlResult->boundValue(placeholder);
1136 }
1137
1138 /*!
1139 Returns the value for the placeholder at position \a pos.
1140 */
boundValue(int pos) const1141 QVariant QSqlQuery::boundValue(int pos) const
1142 {
1143 return d->sqlResult->boundValue(pos);
1144 }
1145
1146 /*!
1147 Returns a map of the bound values.
1148
1149 With named binding, the bound values can be examined in the
1150 following ways:
1151
1152 \snippet sqldatabase/sqldatabase.cpp 14
1153
1154 With positional binding, the code becomes:
1155
1156 \snippet sqldatabase/sqldatabase.cpp 15
1157
1158 \sa boundValue(), bindValue(), addBindValue()
1159 */
boundValues() const1160 QMap<QString,QVariant> QSqlQuery::boundValues() const
1161 {
1162 QMap<QString,QVariant> map;
1163
1164 const QVector<QVariant> values(d->sqlResult->boundValues());
1165 for (int i = 0; i < values.count(); ++i)
1166 map[d->sqlResult->boundValueName(i)] = values.at(i);
1167 return map;
1168 }
1169
1170 /*!
1171 Returns the last query that was successfully executed.
1172
1173 In most cases this function returns the same string as lastQuery().
1174 If a prepared query with placeholders is executed on a DBMS that
1175 does not support it, the preparation of this query is emulated. The
1176 placeholders in the original query are replaced with their bound
1177 values to form a new query. This function returns the modified
1178 query. It is mostly useful for debugging purposes.
1179
1180 \sa lastQuery()
1181 */
executedQuery() const1182 QString QSqlQuery::executedQuery() const
1183 {
1184 return d->sqlResult->executedQuery();
1185 }
1186
1187 /*!
1188 Returns the object ID of the most recent inserted row if the
1189 database supports it. An invalid QVariant will be returned if the
1190 query did not insert any value or if the database does not report
1191 the id back. If more than one row was touched by the insert, the
1192 behavior is undefined.
1193
1194 For MySQL databases the row's auto-increment field will be returned.
1195
1196 \note For this function to work in PSQL, the table table must
1197 contain OIDs, which may not have been created by default. Check the
1198 \c default_with_oids configuration variable to be sure.
1199
1200 \sa QSqlDriver::hasFeature()
1201 */
lastInsertId() const1202 QVariant QSqlQuery::lastInsertId() const
1203 {
1204 return d->sqlResult->lastInsertId();
1205 }
1206
1207 /*!
1208
1209 Instruct the database driver to return numerical values with a
1210 precision specified by \a precisionPolicy.
1211
1212 The Oracle driver, for example, can retrieve numerical values as
1213 strings to prevent the loss of precision. If high precision doesn't
1214 matter, use this method to increase execution speed by bypassing
1215 string conversions.
1216
1217 Note: Drivers that don't support fetching numerical values with low
1218 precision will ignore the precision policy. You can use
1219 QSqlDriver::hasFeature() to find out whether a driver supports this
1220 feature.
1221
1222 Note: Setting the precision policy doesn't affect the currently
1223 active query. Call \l{exec()}{exec(QString)} or prepare() in order
1224 to activate the policy.
1225
1226 \sa QSql::NumericalPrecisionPolicy, numericalPrecisionPolicy()
1227 */
setNumericalPrecisionPolicy(QSql::NumericalPrecisionPolicy precisionPolicy)1228 void QSqlQuery::setNumericalPrecisionPolicy(QSql::NumericalPrecisionPolicy precisionPolicy)
1229 {
1230 d->sqlResult->setNumericalPrecisionPolicy(precisionPolicy);
1231 }
1232
1233 /*!
1234 Returns the current precision policy.
1235
1236 \sa QSql::NumericalPrecisionPolicy, setNumericalPrecisionPolicy()
1237 */
numericalPrecisionPolicy() const1238 QSql::NumericalPrecisionPolicy QSqlQuery::numericalPrecisionPolicy() const
1239 {
1240 return d->sqlResult->numericalPrecisionPolicy();
1241 }
1242
1243 /*!
1244 \since 4.3.2
1245
1246 Instruct the database driver that no more data will be fetched from
1247 this query until it is re-executed. There is normally no need to
1248 call this function, but it may be helpful in order to free resources
1249 such as locks or cursors if you intend to re-use the query at a
1250 later time.
1251
1252 Sets the query to inactive. Bound values retain their values.
1253
1254 \sa prepare(), exec(), isActive()
1255 */
finish()1256 void QSqlQuery::finish()
1257 {
1258 if (isActive()) {
1259 d->sqlResult->setLastError(QSqlError());
1260 d->sqlResult->setAt(QSql::BeforeFirstRow);
1261 d->sqlResult->detachFromResultSet();
1262 d->sqlResult->setActive(false);
1263 }
1264 }
1265
1266 /*!
1267 \since 4.4
1268
1269 Discards the current result set and navigates to the next if available.
1270
1271 Some databases are capable of returning multiple result sets for
1272 stored procedures or SQL batches (a query strings that contains
1273 multiple statements). If multiple result sets are available after
1274 executing a query this function can be used to navigate to the next
1275 result set(s).
1276
1277 If a new result set is available this function will return true.
1278 The query will be repositioned on an \e invalid record in the new
1279 result set and must be navigated to a valid record before data
1280 values can be retrieved. If a new result set isn't available the
1281 function returns \c false and the query is set to inactive. In any
1282 case the old result set will be discarded.
1283
1284 When one of the statements is a non-select statement a count of
1285 affected rows may be available instead of a result set.
1286
1287 Note that some databases, i.e. Microsoft SQL Server, requires
1288 non-scrollable cursors when working with multiple result sets. Some
1289 databases may execute all statements at once while others may delay
1290 the execution until the result set is actually accessed, and some
1291 databases may have restrictions on which statements are allowed to
1292 be used in a SQL batch.
1293
1294 \sa QSqlDriver::hasFeature(), setForwardOnly(), next(), isSelect(),
1295 numRowsAffected(), isActive(), lastError()
1296 */
nextResult()1297 bool QSqlQuery::nextResult()
1298 {
1299 if (isActive())
1300 return d->sqlResult->nextResult();
1301 return false;
1302 }
1303
1304 QT_END_NAMESPACE
1305