source: trunk/src/sql/kernel/qsqlquery.cpp@ 160

Last change on this file since 160 was 2, checked in by Dmitry A. Kuminov, 16 years ago

Initially imported qt-all-opensource-src-4.5.1 from Trolltech.

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