source: trunk/src/sql/qsqlquery.cpp

Last change on this file was 196, checked in by rudi, 14 years ago

Add SQL module (currently it isn't build by default, however it's needed for QtDesigner)

File size: 34.5 KB
Line 
1/****************************************************************************
2**
3** Implementation of QSqlQuery class
4**
5** Created : 2000-11-03
6**
7** Copyright (C) 2000-2007 Trolltech ASA. All rights reserved.
8**
9** This file is part of the sql module of the Qt GUI Toolkit.
10**
11** This file may be distributed under the terms of the Q Public License
12** as defined by Trolltech ASA of Norway and appearing in the file
13** LICENSE.QPL included in the packaging of this file.
14**
15** This file may be distributed and/or modified under the terms of the
16** GNU General Public License version 2 as published by the Free Software
17** Foundation and appearing in the file LICENSE.GPL included in the
18** packaging of this file.
19**
20** Licensees holding valid Qt Enterprise Edition licenses may use this
21** file in accordance with the Qt Commercial License Agreement provided
22** with the Software.
23**
24** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
25** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
26**
27** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
28** information about Qt Commercial License Agreements.
29** See http://www.trolltech.com/qpl/ for QPL licensing information.
30** See http://www.trolltech.com/gpl/ for GPL licensing information.
31**
32** Contact info@trolltech.com if any conditions of this licensing are
33** not clear to you.
34**
35**********************************************************************/
36
37#include "qsqlquery.h"
38
39#ifndef QT_NO_SQL
40
41//#define QT_DEBUG_SQL
42
43#include "qsqlresult.h"
44#include "qsqldriver.h"
45#include "qsqldatabase.h"
46#include "qsql.h"
47#include "qregexp.h"
48#include "private/qsqlextension_p.h"
49
50
51/*!
52\internal
53*/
54QSqlResultShared::QSqlResultShared( QSqlResult* result ): sqlResult(result)
55{
56 if ( result )
57 connect( result->driver(), SIGNAL(destroyed()), this, SLOT(slotResultDestroyed()) );
58}
59
60/*!
61\internal
62*/
63QSqlResultShared::~QSqlResultShared()
64{
65 delete sqlResult;
66}
67
68/*!
69\internal
70
71In case a plugin gets unloaded the pointer to the sqlResult gets invalid
72*/
73void QSqlResultShared::slotResultDestroyed()
74{
75 delete sqlResult;
76 sqlResult = 0;
77}
78
79/*!
80 \class QSqlQuery qsqlquery.h
81 \brief The QSqlQuery class provides a means of executing and
82 manipulating SQL statements.
83
84 \ingroup database
85 \mainclass
86 \module sql
87
88 QSqlQuery encapsulates the functionality involved in creating,
89 navigating and retrieving data from SQL queries which are executed
90 on a \l QSqlDatabase. It can be used to execute DML (data
91 manipulation language) statements, e.g. \c SELECT, \c INSERT, \c
92 UPDATE and \c DELETE, and also DDL (data definition language)
93 statements, e.g. \c{CREATE TABLE}. It can also be used to
94 execute database-specific commands which are not standard SQL
95 (e.g. \c{SET DATESTYLE=ISO} for PostgreSQL).
96
97 Successfully executed SQL statements set the query's state to
98 active (isActive() returns TRUE); otherwise the query's state is
99 set to inactive. In either case, when executing a new SQL
100 statement, the query is positioned on an invalid record; an active
101 query must be navigated to a valid record (so that isValid()
102 returns TRUE) before values can be retrieved.
103
104 Navigating records is performed with the following functions:
105
106 \list
107 \i \c next()
108 \i \c prev()
109 \i \c first()
110 \i \c last()
111 \i \c \link QSqlQuery::seek() seek\endlink(int)
112 \endlist
113
114 These functions allow the programmer to move forward, backward or
115 arbitrarily through the records returned by the query. If you only
116 need to move forward through the results, e.g. using next() or
117 using seek() with a positive offset, you can use setForwardOnly()
118 and save a significant amount of memory overhead. Once an active
119 query is positioned on a valid record, data can be retrieved using
120 value(). All data is transferred from the SQL backend using
121 QVariants.
122
123 For example:
124
125 \code
126 QSqlQuery query( "SELECT name FROM customer" );
127 while ( query.next() ) {
128 QString name = query.value(0).toString();
129 doSomething( name );
130 }
131 \endcode
132
133 To access the data returned by a query, use the value() method.
134 Each field in the data returned by a SELECT statement is accessed
135 by passing the field's position in the statement, starting from 0.
136 Information about the fields can be obtained via QSqlDatabase::record().
137 For the sake of efficiency there are no functions to access a field
138 by name. (The \l QSqlCursor class provides a higher-level interface
139 with field access by name and automatic SQL generation.)
140
141 QSqlQuery supports prepared query execution and the binding of
142 parameter values to placeholders. Some databases don't support
143 these features, so for them Qt emulates the required
144 functionality. For example, the Oracle and ODBC drivers have
145 proper prepared query support, and Qt makes use of it; but for
146 databases that don't have this support, Qt implements the feature
147 itself, e.g. by replacing placeholders with actual values when a
148 query is executed. The exception is positional binding using named
149 placeholders, which requires that the database supports prepared
150 queries.
151
152 Oracle databases identify placeholders by using a colon-name
153 syntax, e.g \c{:name}. ODBC simply uses \c ? characters. Qt
154 supports both syntaxes (although you can't mix them in the same
155 query).
156
157 Below we present the same example using each of the four different
158 binding approaches.
159
160 <b>Named binding using named placeholders</b>
161 \code
162 QSqlQuery query;
163 query.prepare( "INSERT INTO atable (id, forename, surname) "
164 "VALUES (:id, :forename, :surname)" );
165 query.bindValue( ":id", 1001 );
166 query.bindValue( ":forename", "Bart" );
167 query.bindValue( ":surname", "Simpson" );
168 query.exec();
169 \endcode
170
171 <b>Positional binding using named placeholders</b>
172 \code
173 QSqlQuery query;
174 query.prepare( "INSERT INTO atable (id, forename, surname) "
175 "VALUES (:id, :forename, :surname)" );
176 query.bindValue( 0, 1001 );
177 query.bindValue( 1, "Bart" );
178 query.bindValue( 2, "Simpson" );
179 query.exec();
180 \endcode
181 <b>Note:</b> Using positional binding with named placeholders will
182 only work if the database supports prepared queries. This can be
183 checked with QSqlDriver::hasFeature() using QSqlDriver::PreparedQueries
184 as argument for driver feature.
185
186 <b>Binding values using positional placeholders #1</b>
187 \code
188 QSqlQuery query;
189 query.prepare( "INSERT INTO atable (id, forename, surname) "
190 "VALUES (?, ?, ?)" );
191 query.bindValue( 0, 1001 );
192 query.bindValue( 1, "Bart" );
193 query.bindValue( 2, "Simpson" );
194 query.exec();
195 \endcode
196
197 <b>Binding values using positional placeholders #2</b>
198 \code
199 query.prepare( "INSERT INTO atable (id, forename, surname) "
200 "VALUES (?, ?, ?)" );
201 query.addBindValue( 1001 );
202 query.addBindValue( "Bart" );
203 query.addBindValue( "Simpson" );
204 query.exec();
205 \endcode
206
207 <b>Binding values to a stored procedure</b>
208 This code calls a stored procedure called \c AsciiToInt(), passing
209 it a character through its in parameter, and taking its result in
210 the out parameter.
211 \code
212 QSqlQuery query;
213 query.prepare( "call AsciiToInt(?, ?)" );
214 query.bindValue( 0, "A" );
215 query.bindValue( 1, 0, QSql::Out );
216 query.exec();
217 int i = query.boundValue( 1 ).toInt(); // i is 65.
218 \endcode
219
220 \sa QSqlDatabase QSqlCursor QVariant
221*/
222
223/*!
224 Creates a QSqlQuery object which uses the QSqlResult \a r to
225 communicate with a database.
226*/
227
228QSqlQuery::QSqlQuery( QSqlResult * r )
229{
230 d = new QSqlResultShared( r );
231}
232
233/*!
234 Destroys the object and frees any allocated resources.
235*/
236
237QSqlQuery::~QSqlQuery()
238{
239 if (d->deref()) {
240 delete d;
241 }
242}
243
244/*!
245 Constructs a copy of \a other.
246*/
247
248QSqlQuery::QSqlQuery( const QSqlQuery& other )
249 : d(other.d)
250{
251 d->ref();
252}
253
254/*!
255 Creates a QSqlQuery object using the SQL \a query and the database
256 \a db. If \a db is 0, (the default), the application's default
257 database is used. If \a query is not a null string, it will be
258 executed.
259
260 \sa QSqlDatabase
261*/
262QSqlQuery::QSqlQuery( const QString& query, QSqlDatabase* db )
263{
264 init( query, db );
265}
266
267/*!
268 Creates a QSqlQuery object using the database \a db. If \a db is
269 0, the application's default database is used.
270
271 \sa QSqlDatabase
272*/
273
274QSqlQuery::QSqlQuery( QSqlDatabase* db )
275{
276 init( QString::null, db );
277}
278
279/*! \internal
280*/
281
282void QSqlQuery::init( const QString& query, QSqlDatabase* db )
283{
284 d = new QSqlResultShared( 0 );
285 QSqlDatabase* database = db;
286 if ( !database )
287 database = QSqlDatabase::database( QSqlDatabase::defaultConnection, FALSE );
288 if ( database )
289 *this = database->driver()->createQuery();
290 if ( !query.isNull() )
291 exec( query );
292}
293
294/*!
295 Assigns \a other to the query.
296*/
297
298QSqlQuery& QSqlQuery::operator=( const QSqlQuery& other )
299{
300 other.d->ref();
301 deref();
302 d = other.d;
303 return *this;
304}
305
306/*!
307 Returns TRUE if the query is active and positioned on a valid
308 record and the \a field is NULL; otherwise returns FALSE. Note
309 that for some drivers isNull() will not return accurate
310 information until after an attempt is made to retrieve data.
311
312 \sa isActive() isValid() value()
313*/
314
315bool QSqlQuery::isNull( int field ) const
316{
317 if ( !d->sqlResult )
318 return FALSE;
319 if ( d->sqlResult->isActive() && d->sqlResult->isValid() )
320 return d->sqlResult->isNull( field );
321 return FALSE;
322}
323
324/*!
325 Executes the SQL in \a query. Returns TRUE and sets the query
326 state to active if the query was successful; otherwise returns
327 FALSE and sets the query state to inactive. The \a query string
328 must use syntax appropriate for the SQL database being queried,
329 for example, standard SQL.
330
331 After the query is executed, the query is positioned on an \e
332 invalid record, and must be navigated to a valid record before
333 data values can be retrieved, e.g. using next().
334
335 Note that the last error for this query is reset when exec() is
336 called.
337
338 \sa isActive() isValid() next() prev() first() last() seek()
339*/
340
341bool QSqlQuery::exec ( const QString& query )
342{
343 if ( !d->sqlResult )
344 return FALSE;
345 if ( d->sqlResult->extension() && driver()->hasFeature( QSqlDriver::PreparedQueries ) )
346 d->sqlResult->extension()->clear();
347 d->sqlResult->setActive( FALSE );
348 d->sqlResult->setLastError( QSqlError() );
349 d->sqlResult->setAt( QSql::BeforeFirst );
350 if ( !driver() ) {
351#ifdef QT_CHECK_RANGE
352 qWarning("QSqlQuery::exec: no driver" );
353#endif
354 return FALSE;
355 }
356 if ( d->count > 1 )
357 *this = driver()->createQuery();
358 d->sqlResult->setQuery( query.stripWhiteSpace() );
359 d->executedQuery = d->sqlResult->lastQuery();
360 if ( !driver()->isOpen() || driver()->isOpenError() ) {
361#ifdef QT_CHECK_RANGE
362 qWarning("QSqlQuery::exec: database not open" );
363#endif
364 return FALSE;
365 }
366 if ( query.isNull() || query.length() == 0 ) {
367#ifdef QT_CHECK_RANGE
368 qWarning("QSqlQuery::exec: empty query" );
369#endif
370 return FALSE;
371 }
372#ifdef QT_DEBUG_SQL
373 qDebug( "\n QSqlQuery: " + query );
374#endif
375 return d->sqlResult->reset( query );
376}
377
378/*!
379 Returns the value of the \a{i}-th field in the query (zero based).
380
381 The fields are numbered from left to right using the text of the
382 \c SELECT statement, e.g. in \c{SELECT forename, surname FROM people},
383 field 0 is \c forename and field 1 is \c surname. Using \c{SELECT *}
384 is not recommended because the order of the fields in the query is
385 undefined.
386
387 An invalid QVariant is returned if field \a i does not exist, if
388 the query is inactive, or if the query is positioned on an invalid
389 record.
390
391 \sa prev() next() first() last() seek() isActive() isValid()
392*/
393
394QVariant QSqlQuery::value( int i ) const
395{
396 if ( !d->sqlResult )
397 return QVariant();
398 if ( isActive() && isValid() && ( i > QSql::BeforeFirst ) ) {
399 return d->sqlResult->data( i );
400 } else {
401#ifdef QT_CHECK_RANGE
402 qWarning( "QSqlQuery::value: not positioned on a valid record" );
403#endif
404 }
405 return QVariant();
406}
407
408/*!
409 Returns the current internal position of the query. The first
410 record is at position zero. If the position is invalid, a
411 QSql::Location will be returned indicating the invalid position.
412
413 \sa prev() next() first() last() seek() isActive() isValid()
414*/
415
416int QSqlQuery::at() const
417{
418 if ( !d->sqlResult )
419 return QSql::BeforeFirst;
420 return d->sqlResult->at();
421}
422
423/*!
424 Returns the text of the current query being used, or QString::null
425 if there is no current query text.
426
427 \sa executedQuery()
428*/
429
430QString QSqlQuery::lastQuery() const
431{
432 if ( !d->sqlResult )
433 return QString::null;
434 return d->sqlResult->lastQuery();
435}
436
437/*!
438 Returns the database driver associated with the query.
439*/
440
441const QSqlDriver* QSqlQuery::driver() const
442{
443 if ( !d->sqlResult )
444 return 0;
445 return d->sqlResult->driver();
446}
447
448/*!
449 Returns the result associated with the query.
450*/
451
452const QSqlResult* QSqlQuery::result() const
453{
454 return d->sqlResult;
455}
456
457/*!
458 Retrieves the record at position (offset) \a i, if available, and
459 positions the query on the retrieved record. The first record is
460 at position 0. Note that the query must be in an active state and
461 isSelect() must return TRUE before calling this function.
462
463 If \a relative is FALSE (the default), the following rules apply:
464
465 \list
466 \i If \a i is negative, the result is positioned before the
467 first record and FALSE is returned.
468 \i Otherwise, an attempt is made to move to the record at position
469 \a i. If the record at position \a i could not be retrieved, the
470 result is positioned after the last record and FALSE is returned. If
471 the record is successfully retrieved, TRUE is returned.
472 \endlist
473
474 If \a relative is TRUE, the following rules apply:
475
476 \list
477 \i If the result is currently positioned before the first
478 record or on the first record, and \a i is negative, there is no
479 change, and FALSE is returned.
480 \i If the result is currently located after the last record, and
481 \a i is positive, there is no change, and FALSE is returned.
482 \i If the result is currently located somewhere in the middle,
483 and the relative offset \a i moves the result below zero, the
484 result is positioned before the first record and FALSE is
485 returned.
486 \i Otherwise, an attempt is made to move to the record \a i
487 records ahead of the current record (or \a i records behind the
488 current record if \a i is negative). If the record at offset \a i
489 could not be retrieved, the result is positioned after the last
490 record if \a i >= 0, (or before the first record if \a i is
491 negative), and FALSE is returned. If the record is successfully
492 retrieved, TRUE is returned.
493 \endlist
494
495 \sa next() prev() first() last() at() isActive() isValid()
496*/
497bool QSqlQuery::seek( int i, bool relative )
498{
499 if ( !isSelect() || !isActive() )
500 return FALSE;
501 beforeSeek();
502 checkDetach();
503 int actualIdx;
504 if ( !relative ) { // arbitrary seek
505 if ( i < 0 ) {
506 d->sqlResult->setAt( QSql::BeforeFirst );
507 afterSeek();
508 return FALSE;
509 }
510 actualIdx = i;
511 } else {
512 switch ( at() ) { // relative seek
513 case QSql::BeforeFirst:
514 if ( i > 0 )
515 actualIdx = i;
516 else {
517 afterSeek();
518 return FALSE;
519 }
520 break;
521 case QSql::AfterLast:
522 if ( i < 0 ) {
523 d->sqlResult->fetchLast();
524 actualIdx = at() + i;
525 } else {
526 afterSeek();
527 return FALSE;
528 }
529 break;
530 default:
531 if ( ( at() + i ) < 0 ) {
532 d->sqlResult->setAt( QSql::BeforeFirst );
533 afterSeek();
534 return FALSE;
535 }
536 actualIdx = at() + i;
537 break;
538 }
539 }
540 // let drivers optimize
541 if ( isForwardOnly() && actualIdx < at() ) {
542#ifdef QT_CHECK_RANGE
543 qWarning("QSqlQuery::seek: cannot seek backwards in a forward only query" );
544#endif
545 afterSeek();
546 return FALSE;
547 }
548 if ( actualIdx == ( at() + 1 ) && at() != QSql::BeforeFirst ) {
549 if ( !d->sqlResult->fetchNext() ) {
550 d->sqlResult->setAt( QSql::AfterLast );
551 afterSeek();
552 return FALSE;
553 }
554 afterSeek();
555 return TRUE;
556 }
557 if ( actualIdx == ( at() - 1 ) ) {
558 if ( !d->sqlResult->fetchPrev() ) {
559 d->sqlResult->setAt( QSql::BeforeFirst );
560 afterSeek();
561 return FALSE;
562 }
563 afterSeek();
564 return TRUE;
565 }
566 if ( !d->sqlResult->fetch( actualIdx ) ) {
567 d->sqlResult->setAt( QSql::AfterLast );
568 afterSeek();
569 return FALSE;
570 }
571 afterSeek();
572 return TRUE;
573}
574
575/*!
576 Retrieves the next record in the result, if available, and
577 positions the query on the retrieved record. Note that the result
578 must be in an active state and isSelect() must return TRUE before
579 calling this function or it will do nothing and return FALSE.
580
581 The following rules apply:
582
583 \list
584 \i If the result is currently located before the first
585 record, e.g. immediately after a query is executed, an attempt is
586 made to retrieve the first record.
587
588 \i If the result is currently located after the last record,
589 there is no change and FALSE is returned.
590
591 \i If the result is located somewhere in the middle, an attempt
592 is made to retrieve the next record.
593 \endlist
594
595 If the record could not be retrieved, the result is positioned after
596 the last record and FALSE is returned. If the record is successfully
597 retrieved, TRUE is returned.
598
599 \sa prev() first() last() seek() at() isActive() isValid()
600*/
601
602bool QSqlQuery::next()
603{
604 if ( !isSelect() || !isActive() )
605 return FALSE;
606 beforeSeek();
607 checkDetach();
608 bool b = FALSE;
609 switch ( at() ) {
610 case QSql::BeforeFirst:
611 b = d->sqlResult->fetchFirst();
612 afterSeek();
613 return b;
614 case QSql::AfterLast:
615 afterSeek();
616 return FALSE;
617 default:
618 if ( !d->sqlResult->fetchNext() ) {
619 d->sqlResult->setAt( QSql::AfterLast );
620 afterSeek();
621 return FALSE;
622 }
623 afterSeek();
624 return TRUE;
625 }
626}
627
628/*!
629 Retrieves the previous record in the result, if available, and
630 positions the query on the retrieved record. Note that the result
631 must be in an active state and isSelect() must return TRUE before
632 calling this function or it will do nothing and return FALSE.
633
634 The following rules apply:
635
636 \list
637 \i If the result is currently located before the first record,
638 there is no change and FALSE is returned.
639
640 \i If the result is currently located after the last record, an
641 attempt is made to retrieve the last record.
642
643 \i If the result is somewhere in the middle, an attempt is made
644 to retrieve the previous record.
645 \endlist
646
647 If the record could not be retrieved, the result is positioned
648 before the first record and FALSE is returned. If the record is
649 successfully retrieved, TRUE is returned.
650
651 \sa next() first() last() seek() at() isActive() isValid()
652*/
653
654bool QSqlQuery::prev()
655{
656 if ( !isSelect() || !isActive() )
657 return FALSE;
658 if ( isForwardOnly() ) {
659#ifdef QT_CHECK_RANGE
660 qWarning("QSqlQuery::seek: cannot seek backwards in a forward only query" );
661#endif
662 return FALSE;
663 }
664
665 beforeSeek();
666 checkDetach();
667 bool b = FALSE;
668 switch ( at() ) {
669 case QSql::BeforeFirst:
670 afterSeek();
671 return FALSE;
672 case QSql::AfterLast:
673 b = d->sqlResult->fetchLast();
674 afterSeek();
675 return b;
676 default:
677 if ( !d->sqlResult->fetchPrev() ) {
678 d->sqlResult->setAt( QSql::BeforeFirst );
679 afterSeek();
680 return FALSE;
681 }
682 afterSeek();
683 return TRUE;
684 }
685}
686
687/*!
688 Retrieves the first record in the result, if available, and
689 positions the query on the retrieved record. Note that the result
690 must be in an active state and isSelect() must return TRUE before
691 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() prev() last() seek() at() isActive() isValid()
696*/
697
698bool QSqlQuery::first()
699{
700 if ( !isSelect() || !isActive() )
701 return FALSE;
702 if ( isForwardOnly() && at() > QSql::BeforeFirst ) {
703#ifdef QT_CHECK_RANGE
704 qWarning("QSqlQuery::seek: cannot seek backwards in a forward only query" );
705#endif
706 return FALSE;
707 }
708 beforeSeek();
709 checkDetach();
710 bool b = FALSE;
711 b = d->sqlResult->fetchFirst();
712 afterSeek();
713 return b;
714}
715
716/*!
717 Retrieves the last record in the result, if available, and
718 positions the query on the retrieved record. Note that the result
719 must be in an active state and isSelect() must return TRUE before
720 calling this function or it will do nothing and return FALSE.
721 Returns TRUE if successful. If unsuccessful the query position is
722 set to an invalid position and FALSE is returned.
723
724 \sa next() prev() first() seek() at() isActive() isValid()
725*/
726
727bool QSqlQuery::last()
728{
729 if ( !isSelect() || !isActive() )
730 return FALSE;
731 beforeSeek();
732 checkDetach();
733 bool b = FALSE;
734 b = d->sqlResult->fetchLast();
735 afterSeek();
736 return b;
737}
738
739/*!
740 Returns the size of the result, (number of rows returned), or -1
741 if the size cannot be determined or if the database does not
742 support reporting information about query sizes. Note that for
743 non-\c SELECT statements (isSelect() returns FALSE), size() will
744 return -1. If the query is not active (isActive() returns FALSE),
745 -1 is returned.
746
747 To determine the number of rows affected by a non-SELECT
748 statement, use numRowsAffected().
749
750 \sa isActive() numRowsAffected() QSqlDriver::hasFeature()
751*/
752int QSqlQuery::size() const
753{
754 if ( !d->sqlResult )
755 return -1;
756 if ( isActive() && d->sqlResult->driver()->hasFeature( QSqlDriver::QuerySize ) )
757 return d->sqlResult->size();
758 return -1;
759}
760
761/*!
762 Returns the number of rows affected by the result's SQL statement,
763 or -1 if it cannot be determined. Note that for \c SELECT
764 statements, the value is undefined; see size() instead. If the
765 query is not active (isActive() returns FALSE), -1 is returned.
766
767 \sa size() QSqlDriver::hasFeature()
768*/
769
770int QSqlQuery::numRowsAffected() const
771{
772 if ( !d->sqlResult )
773 return -1;
774 if ( isActive() )
775 return d->sqlResult->numRowsAffected();
776 return -1;
777}
778
779/*!
780 Returns error information about the last error (if any) that
781 occurred.
782
783 \sa QSqlError
784*/
785
786QSqlError QSqlQuery::lastError() const
787{
788 if ( !d->sqlResult )
789 return QSqlError();
790 return d->sqlResult->lastError();
791}
792
793/*!
794 Returns TRUE if the query is currently positioned on a valid
795 record; otherwise returns FALSE.
796*/
797
798bool QSqlQuery::isValid() const
799{
800 if ( !d->sqlResult )
801 return FALSE;
802 return d->sqlResult->isValid();
803}
804
805/*!
806 Returns TRUE if the query is currently active; otherwise returns
807 FALSE.
808*/
809
810bool QSqlQuery::isActive() const
811{
812 if ( !d->sqlResult )
813 return FALSE;
814 return d->sqlResult->isActive();
815}
816
817/*!
818 Returns TRUE if the current query is a \c SELECT statement;
819 otherwise returns FALSE.
820*/
821
822bool QSqlQuery::isSelect() const
823{
824 if ( !d->sqlResult )
825 return FALSE;
826 return d->sqlResult->isSelect();
827}
828
829/*!
830 Returns TRUE if you can only scroll \e forward through a result
831 set; otherwise returns FALSE.
832
833 \sa setForwardOnly()
834*/
835bool QSqlQuery::isForwardOnly() const
836{
837 if ( !d->sqlResult )
838 return FALSE;
839 return d->sqlResult->isForwardOnly();
840}
841
842/*!
843 Sets forward only mode to \a forward. If forward is TRUE only
844 next(), and seek() with positive values, are allowed for
845 navigating the results. Forward only mode needs far less memory
846 since results do not need to be cached.
847
848 Forward only mode is off by default.
849
850 Forward only mode cannot be used with data aware widgets like
851 QDataTable, since they must to be able to scroll backward as well
852 as forward.
853
854 \sa isForwardOnly(), next(), seek()
855*/
856void QSqlQuery::setForwardOnly( bool forward )
857{
858 if ( d->sqlResult )
859 d->sqlResult->setForwardOnly( forward );
860}
861
862/*!
863 \internal
864*/
865
866void QSqlQuery::deref()
867{
868 if ( d->deref() ) {
869 delete d;
870 d = 0;
871 }
872}
873
874/*!
875 \internal
876*/
877
878bool QSqlQuery::checkDetach()
879{
880 if ( d->count > 1 && d->sqlResult ) {
881 QString sql = d->sqlResult->lastQuery();
882 *this = driver()->createQuery();
883 exec( sql );
884 return TRUE;
885 }
886 return FALSE;
887}
888
889
890/*!
891 Protected virtual function called before the internal record
892 pointer is moved to a new record. The default implementation does
893 nothing.
894*/
895
896void QSqlQuery::beforeSeek()
897{
898
899}
900
901
902/*!
903 Protected virtual function called after the internal record
904 pointer is moved to a new record. The default implementation does
905 nothing.
906*/
907
908void QSqlQuery::afterSeek()
909{
910
911}
912
913// XXX: Hack to keep BCI - remove in 4.0. QSqlExtension should be
914// removed, and the prepare(), exec() etc. fu's should be
915// made virtual members of QSqlQuery/QSqlResult
916
917/*!
918 Prepares the SQL query \a query for execution. The query may
919 contain placeholders for binding values. Both Oracle style
920 colon-name (e.g. \c{:surname}), and ODBC style (e.g. \c{?})
921 placeholders are supported; but they cannot be mixed in the same
922 query. See the \link #details Description\endlink for examples.
923
924 \sa exec(), bindValue(), addBindValue()
925*/
926bool QSqlQuery::prepare( const QString& query )
927{
928 if ( !d->sqlResult || !d->sqlResult->extension() )
929 return FALSE;
930 d->sqlResult->setActive( FALSE );
931 d->sqlResult->setLastError( QSqlError() );
932 d->sqlResult->setAt( QSql::BeforeFirst );
933 d->sqlResult->extension()->clear();
934 if ( !driver() ) {
935#ifdef QT_CHECK_RANGE
936 qWarning("QSqlQuery::prepare: no driver" );
937#endif
938 return FALSE;
939 }
940 if ( d->count > 1 )
941 *this = driver()->createQuery();
942 d->sqlResult->setQuery( query.stripWhiteSpace() );
943 if ( !driver()->isOpen() || driver()->isOpenError() ) {
944#ifdef QT_CHECK_RANGE
945 qWarning("QSqlQuery::prepare: database not open" );
946#endif
947 return FALSE;
948 }
949 if ( query.isNull() || query.length() == 0 ) {
950#ifdef QT_CHECK_RANGE
951 qWarning("QSqlQuery::prepare: empty query" );
952#endif
953 return FALSE;
954 }
955#ifdef QT_DEBUG_SQL
956 qDebug( "\n QSqlQuery: " + query );
957#endif
958 QString q = query;
959 QRegExp rx(QString::fromLatin1("'[^']*'|:([a-zA-Z0-9_]+)"));
960 if ( driver()->hasFeature( QSqlDriver::PreparedQueries ) ) {
961 // below we substitute Oracle placeholders with ODBC ones and
962 // vice versa to make this db independent
963 int i = 0, cnt = 0;
964 if ( driver()->hasFeature( QSqlDriver::NamedPlaceholders ) ) {
965 QRegExp rx(QString::fromLatin1("'[^']*'|\\?"));
966 while ( (i = rx.search( q, i )) != -1 ) {
967 if ( rx.cap(0) == "?" ) {
968 q = q.replace( i, 1, ":f" + QString::number(cnt) );
969 cnt++;
970 }
971 i += rx.matchedLength();
972 }
973 } else if ( driver()->hasFeature( QSqlDriver::PositionalPlaceholders ) ) {
974 while ( (i = rx.search( q, i )) != -1 ) {
975 if ( rx.cap(1).isEmpty() ) {
976 i += rx.matchedLength();
977 } else {
978 // record the index of the placeholder - needed
979 // for emulating named bindings with ODBC
980 d->sqlResult->extension()->index[ cnt ]= rx.cap(0);
981 q = q.replace( i, rx.matchedLength(), "?" );
982 i++;
983 cnt++;
984 }
985 }
986 }
987 d->executedQuery = q;
988 return d->sqlResult->extension()->prepare( q );
989 } else {
990 int i = 0;
991 while ( (i = rx.search( q, i )) != -1 ) {
992 if ( !rx.cap(1).isEmpty() )
993 d->sqlResult->extension()->holders.append( Holder( rx.cap(0), i ) );
994 i += rx.matchedLength();
995 }
996 return TRUE; // fake prepares should always succeed
997 }
998}
999
1000/*!
1001 \overload
1002
1003 Executes a previously prepared SQL query. Returns TRUE if the
1004 query executed successfully; otherwise returns FALSE.
1005
1006 \sa prepare(), bindValue(), addBindValue()
1007*/
1008bool QSqlQuery::exec()
1009{
1010 bool ret;
1011 if ( !d->sqlResult || !d->sqlResult->extension() )
1012 return FALSE;
1013 if ( driver()->hasFeature( QSqlDriver::PreparedQueries ) ) {
1014 ret = d->sqlResult->extension()->exec();
1015 } else {
1016 // fake preparation - just replace the placeholders..
1017 QString query = d->sqlResult->lastQuery();
1018 if ( d->sqlResult->extension()->bindMethod() == QSqlExtension::BindByName ) {
1019 int i;
1020 QVariant val;
1021 QString holder;
1022 for ( i = (int)d->sqlResult->extension()->holders.count() - 1; i >= 0; --i ) {
1023 holder = d->sqlResult->extension()->holders[ (uint)i ].holderName;
1024 val = d->sqlResult->extension()->values[ holder ].value;
1025 QSqlField f( "", val.type() );
1026 if ( val.isNull() )
1027 f.setNull();
1028 else
1029 f.setValue( val );
1030 query = query.replace( (uint)d->sqlResult->extension()->holders[ (uint)i ].holderPos,
1031 holder.length(), driver()->formatValue( &f ) );
1032 }
1033 } else {
1034 QMap<int, QString>::ConstIterator it;
1035 QString val;
1036 int i = 0;
1037 for ( it = d->sqlResult->extension()->index.begin();
1038 it != d->sqlResult->extension()->index.end(); ++it ) {
1039 i = query.find( '?', i );
1040 if ( i > -1 ) {
1041 QSqlField f( "", d->sqlResult->extension()->values[ it.data() ].value.type() );
1042 if ( d->sqlResult->extension()->values[ it.data() ].value.isNull() )
1043 f.setNull();
1044 else
1045 f.setValue( d->sqlResult->extension()->values[ it.data() ].value );
1046 val = driver()->formatValue( &f );
1047 query = query.replace( i, 1, driver()->formatValue( &f ) );
1048 i += val.length();
1049 }
1050 }
1051 }
1052 // have to retain the original query w/placeholders..
1053 QString orig = d->sqlResult->lastQuery();
1054 ret = exec( query );
1055 d->executedQuery = query;
1056 d->sqlResult->setQuery( orig );
1057 }
1058 d->sqlResult->extension()->resetBindCount();
1059 return ret;
1060}
1061
1062/*!
1063 Set the placeholder \a placeholder to be bound to value \a val in
1064 the prepared statement. Note that the placeholder mark (e.g \c{:})
1065 must be included when specifying the placeholder name. If \a type
1066 is \c QSql::Out or \c QSql::InOut, the placeholder will be
1067 overwritten with data from the database after the exec() call.
1068
1069 \sa addBindValue(), prepare(), exec()
1070*/
1071void QSqlQuery::bindValue( const QString& placeholder, const QVariant& val, QSql::ParameterType type )
1072{
1073 if ( !d->sqlResult || !d->sqlResult->extension() )
1074 return;
1075 d->sqlResult->extension()->bindValue( placeholder, val, type );
1076}
1077
1078/*!
1079 \overload
1080
1081 Set the placeholder in position \a pos to be bound to value \a val
1082 in the prepared statement. Field numbering starts at 0. If \a type
1083 is \c QSql::Out or \c QSql::InOut, the placeholder will be
1084 overwritten with data from the database after the exec() call.
1085
1086 \sa addBindValue(), prepare(), exec()
1087*/
1088void QSqlQuery::bindValue( int pos, const QVariant& val, QSql::ParameterType type )
1089{
1090 if ( !d->sqlResult || !d->sqlResult->extension() )
1091 return;
1092 d->sqlResult->extension()->bindValue( pos, val, type );
1093}
1094
1095/*!
1096 Adds the value \a val to the list of values when using positional
1097 value binding. The order of the addBindValue() calls determines
1098 which placeholder a value will be bound to in the prepared query.
1099 If \a type is \c QSql::Out or \c QSql::InOut, the placeholder will
1100 be overwritten with data from the database after the exec() call.
1101
1102 \sa bindValue(), prepare(), exec()
1103*/
1104void QSqlQuery::addBindValue( const QVariant& val, QSql::ParameterType type )
1105{
1106 if ( !d->sqlResult || !d->sqlResult->extension() )
1107 return;
1108 d->sqlResult->extension()->addBindValue( val, type );
1109}
1110
1111
1112/*!
1113 \overload
1114
1115 Binds the placeholder with type \c QSql::In.
1116*/
1117void QSqlQuery::bindValue( const QString& placeholder, const QVariant& val )
1118{
1119 bindValue( placeholder, val, QSql::In );
1120}
1121
1122/*!
1123 \overload
1124
1125 Binds the placeholder at position \a pos with type \c QSql::In.
1126*/
1127void QSqlQuery::bindValue( int pos, const QVariant& val )
1128{
1129 bindValue( pos, val, QSql::In );
1130}
1131
1132/*!
1133 \overload
1134
1135 Binds the placeholder with type \c QSql::In.
1136*/
1137void QSqlQuery::addBindValue( const QVariant& val )
1138{
1139 addBindValue( val, QSql::In );
1140}
1141
1142/*!
1143 Returns the value for the \a placeholder.
1144*/
1145QVariant QSqlQuery::boundValue( const QString& placeholder ) const
1146{
1147 if ( !d->sqlResult || !d->sqlResult->extension() )
1148 return QVariant();
1149 return d->sqlResult->extension()->boundValue( placeholder );
1150}
1151
1152/*!
1153 \overload
1154
1155 Returns the value for the placeholder at position \a pos.
1156*/
1157QVariant QSqlQuery::boundValue( int pos ) const
1158{
1159 if ( !d->sqlResult || !d->sqlResult->extension() )
1160 return QVariant();
1161 return d->sqlResult->extension()->boundValue( pos );
1162}
1163
1164/*!
1165 Returns a map of the bound values.
1166
1167 The bound values can be examined in the following way:
1168 \code
1169 QSqlQuery query;
1170 ...
1171 // Examine the bound values - bound using named binding
1172 QMap<QString, QVariant>::ConstIterator it;
1173 QMap<QString, QVariant> vals = query.boundValues();
1174 for ( it = vals.begin(); it != vals.end(); ++it )
1175 qWarning( "Placeholder: " + it.key() + ", Value: " + (*it).toString() );
1176 ...
1177
1178 // Examine the bound values - bound using positional binding
1179 QValueList<QVariant>::ConstIterator it;
1180 QValueList<QVariant> list = query.boundValues().values();
1181 int i = 0;
1182 for ( it = list.begin(); it != list.end(); ++it )
1183 qWarning( "Placeholder pos: %d, Value: " + (*it).toString(), i++ );
1184 ...
1185
1186 \endcode
1187*/
1188QMap<QString,QVariant> QSqlQuery::boundValues() const
1189{
1190 if ( !d->sqlResult || !d->sqlResult->extension() )
1191 return QMap<QString,QVariant>();
1192 return d->sqlResult->extension()->boundValues();
1193}
1194
1195/*!
1196 Returns the last query that was executed.
1197
1198 In most cases this function returns the same as lastQuery(). If a
1199 prepared query with placeholders is executed on a DBMS that does
1200 not support it, the preparation of this query is emulated. The
1201 placeholders in the original query are replaced with their bound
1202 values to form a new query. This function returns the modified
1203 query. Useful for debugging purposes.
1204
1205 \sa lastQuery()
1206*/
1207QString QSqlQuery::executedQuery() const
1208{
1209 return d->executedQuery;
1210}
1211#endif // QT_NO_SQL
Note: See TracBrowser for help on using the repository browser.