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