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

Provided by KDAB

Privacy Policy
Start learning QML with our Intro Training
Find out more

source code of qtbase/src/sql/kernel/qsqlquery.cpp