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