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