1 /****************************************************************************
3 ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
4 ** All rights reserved.
5 ** Contact: Nokia Corporation (qt-info@nokia.com)
7 ** This file is part of the QtSql module of the Qt Toolkit.
9 ** $QT_BEGIN_LICENSE:LGPL$
11 ** Licensees holding valid Qt Commercial licenses may use this file in
12 ** accordance with the Qt Commercial License Agreement provided with the
13 ** Software or, alternatively, in accordance with the terms contained in
14 ** a written agreement between you and Nokia.
16 ** GNU Lesser General Public License Usage
17 ** Alternatively, this file may be used under the terms of the GNU Lesser
18 ** General Public License version 2.1 as published by the Free Software
19 ** Foundation and appearing in the file LICENSE.LGPL included in the
20 ** packaging of this file. Please review the following information to
21 ** ensure the GNU Lesser General Public License version 2.1 requirements
22 ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
24 ** In addition, as a special exception, Nokia gives you certain additional
25 ** rights. These rights are described in the Nokia Qt LGPL Exception
26 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
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.
36 ** If you have questions regarding the use of this file, please contact
37 ** Nokia at qt-info@nokia.com.
40 ****************************************************************************/
42 #include "qsqldatabase.h"
43 #include "qsqlquery.h"
46 // Conflicting declarations of LPCBYTE in sqlfront.h and winscard.h
51 #include "../drivers/psql/qsql_psql.h"
54 #include "../drivers/mysql/qsql_mysql.h"
57 #include "../drivers/odbc/qsql_odbc.h"
60 #include "../drivers/oci/qsql_oci.h"
63 #include "../drivers/tds/qsql_tds.h"
66 #include "../drivers/db2/qsql_db2.h"
69 #include "../drivers/sqlite/qsql_sqlite.h"
72 #include "../drivers/sqlite2/qsql_sqlite2.h"
75 #undef SQL_FLOAT // avoid clash with ODBC
81 #define SCHAR IBASE_SCHAR // avoid clash with ODBC (older versions of ibase.h with Firebird)
82 #include "../drivers/ibase/qsql_ibase.h"
87 #include "qcoreapplication.h"
88 #include "qreadwritelock.h"
89 #include "qsqlresult.h"
90 #include "qsqldriver.h"
91 #include "qsqldriverplugin.h"
92 #include "qsqlindex.h"
93 #include "private/qfactoryloader_p.h"
94 #include "private/qsqlnulldriver_p.h"
101 #if !defined(QT_NO_LIBRARY) && !defined(QT_NO_SETTINGS)
102 Q_GLOBAL_STATIC_WITH_ARGS(QFactoryLoader
, loader
,
103 (QSqlDriverFactoryInterface_iid
,
104 QLatin1String("/sqldrivers")))
107 QT_STATIC_CONST_IMPL
char *QSqlDatabase::defaultConnection
= "qt_sql_default_connection";
109 typedef QHash
<QString
, QSqlDriverCreatorBase
*> DriverDict
;
111 class QConnectionDict
: public QHash
<QString
, QSqlDatabase
>
114 inline bool contains_ts(const QString
&key
)
116 QReadLocker
locker(&lock
);
117 return contains(key
);
119 inline QStringList
keys_ts() const
121 QReadLocker
locker(&lock
);
125 mutable QReadWriteLock lock
;
127 Q_GLOBAL_STATIC(QConnectionDict
, dbDict
)
129 class QSqlDatabasePrivate
132 QSqlDatabasePrivate(QSqlDriver
*dr
= 0):
138 QSqlDatabasePrivate(const QSqlDatabasePrivate
&other
);
139 ~QSqlDatabasePrivate();
140 void init(const QString
& type
);
141 void copy(const QSqlDatabasePrivate
*other
);
155 static QSqlDatabasePrivate
*shared_null();
156 static QSqlDatabase
database(const QString
& name
, bool open
);
157 static void addDatabase(const QSqlDatabase
&db
, const QString
& name
);
158 static void removeDatabase(const QString
& name
);
159 static void invalidateDb(const QSqlDatabase
&db
, const QString
&name
);
160 static DriverDict
&driverDict();
161 static void cleanConnections();
164 QSqlDatabasePrivate::QSqlDatabasePrivate(const QSqlDatabasePrivate
&other
)
167 dbname
= other
.dbname
;
171 drvName
= other
.drvName
;
173 connOptions
= other
.connOptions
;
174 driver
= other
.driver
;
177 QSqlDatabasePrivate::~QSqlDatabasePrivate()
179 if (driver
!= shared_null()->driver
)
183 void QSqlDatabasePrivate::cleanConnections()
185 QConnectionDict
*dict
= dbDict();
187 QWriteLocker
locker(&dict
->lock
);
189 QConnectionDict::iterator it
= dict
->begin();
190 while (it
!= dict
->end()) {
191 invalidateDb(it
.value(), it
.key());
197 static bool qDriverDictInit
= false;
198 static void cleanDriverDict()
200 qDeleteAll(QSqlDatabasePrivate::driverDict());
201 QSqlDatabasePrivate::driverDict().clear();
202 QSqlDatabasePrivate::cleanConnections();
203 qDriverDictInit
= false;
206 DriverDict
&QSqlDatabasePrivate::driverDict()
208 static DriverDict dict
;
209 if (!qDriverDictInit
) {
210 qDriverDictInit
= true;
211 qAddPostRoutine(cleanDriverDict
);
216 QSqlDatabasePrivate
*QSqlDatabasePrivate::shared_null()
218 static QSqlNullDriver dr
;
219 static QSqlDatabasePrivate
n(&dr
);
223 void QSqlDatabasePrivate::invalidateDb(const QSqlDatabase
&db
, const QString
&name
)
225 if (db
.d
->ref
!= 1) {
226 qWarning("QSqlDatabasePrivate::removeDatabase: connection '%s' is still in use, "
227 "all queries will cease to work.", name
.toLocal8Bit().constData());
229 db
.d
->connName
.clear();
233 void QSqlDatabasePrivate::removeDatabase(const QString
&name
)
235 QConnectionDict
*dict
= dbDict();
237 QWriteLocker
locker(&dict
->lock
);
239 if (!dict
->contains(name
))
242 invalidateDb(dict
->take(name
), name
);
245 void QSqlDatabasePrivate::addDatabase(const QSqlDatabase
&db
, const QString
&name
)
247 QConnectionDict
*dict
= dbDict();
249 QWriteLocker
locker(&dict
->lock
);
251 if (dict
->contains(name
)) {
252 invalidateDb(dict
->take(name
), name
);
253 qWarning("QSqlDatabasePrivate::addDatabase: duplicate connection name '%s', old "
254 "connection removed.", name
.toLocal8Bit().data());
256 dict
->insert(name
, db
);
257 db
.d
->connName
= name
;
262 QSqlDatabase
QSqlDatabasePrivate::database(const QString
& name
, bool open
)
264 const QConnectionDict
*dict
= dbDict();
267 dict
->lock
.lockForRead();
268 QSqlDatabase db
= dict
->value(name
);
270 if (db
.isValid() && !db
.isOpen() && open
) {
272 qWarning() << "QSqlDatabasePrivate::database: unable to open database:" << db
.lastError().text();
280 Copies the connection data from \a other.
282 void QSqlDatabasePrivate::copy(const QSqlDatabasePrivate
*other
)
284 dbname
= other
->dbname
;
285 uname
= other
->uname
;
286 pword
= other
->pword
;
287 hname
= other
->hname
;
288 drvName
= other
->drvName
;
290 connOptions
= other
->connOptions
;
293 void QSqlDatabasePrivate::disable()
295 if (driver
!= shared_null()->driver
) {
297 driver
= shared_null()->driver
;
302 \class QSqlDriverCreatorBase
303 \brief The QSqlDriverCreatorBase class is the base class for
304 SQL driver factories.
309 Reimplement createObject() to return an instance of the specific
310 QSqlDriver subclass that you want to provide.
312 See QSqlDatabase::registerSqlDriver() for details.
314 \sa QSqlDriverCreator
318 \fn QSqlDriverCreatorBase::~QSqlDriverCreatorBase()
320 Destroys the SQL driver creator object.
324 \fn QSqlDriver *QSqlDriverCreatorBase::createObject() const
326 Reimplement this function to returns a new instance of a
331 \class QSqlDriverCreator
332 \brief The QSqlDriverCreator class is a template class that
333 provides a SQL driver factory for a specific driver type.
338 QSqlDriverCreator<T> instantiates objects of type T, where T is a
341 See QSqlDatabase::registerSqlDriver() for details.
345 \fn QSqlDriver *QSqlDriverCreator::createObject() const
351 \brief The QSqlDatabase class represents a connection to
358 The QSqlDatabase class provides an interface for accessing a
359 database through a connection. An instance of QSqlDatabase
360 represents the connection. The connection provides access to the
361 database via one of the \l{SQL Database Drivers#Supported
362 Databases} {supported database drivers}, which are derived from
363 QSqlDriver. Alternatively, you can subclass your own database
364 driver from QSqlDriver. See \l{How to Write Your Own Database
365 Driver} for more information.
367 Create a connection (i.e., an instance of QSqlDatabase) by calling
368 one of the static addDatabase() functions, where you specify
369 \l{SQL Database Drivers#Supported Databases} {the driver or type
370 of driver} to use (i.e., what kind of database will you access?)
371 and a connection name. A connection is known by its own name,
372 \e{not} by the name of the database it connects to. You can have
373 multiple connections to one database. QSqlDatabase also supports
374 the concept of a \e{default} connection, which is the unnamed
375 connection. To create the default connection, don't pass the
376 connection name argument when you call addDatabase().
377 Subsequently, when you call any static member function that takes
378 the connection name argument, if you don't pass the connection
379 name argument, the default connection is assumed. The following
380 snippet shows how to create and open a default connection to a
383 \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 0
385 Once the QSqlDatabase object has been created, set the connection
386 parameters with setDatabaseName(), setUserName(), setPassword(),
387 setHostName(), setPort(), and setConnectOptions(). Then call
388 open() to activate the physical connection to the database. The
389 connection is not usable until you open it.
391 The connection defined above will be the \e{default} connection,
392 because we didn't give a connection name to \l{QSqlDatabase::}
393 {addDatabase()}. Subsequently, you can get the default connection
394 by calling database() without the connection name argument:
396 \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 1
398 QSqlDatabase is a value class. Changes made to a database
399 connection via one instance of QSqlDatabase will affect other
400 instances of QSqlDatabase that represent the same connection. Use
401 cloneDatabase() to create an independent database connection based
404 If you create multiple database connections, specify a unique
405 connection name for each one, when you call addDatabase(). Use
406 database() with a connection name to get that connection. Use
407 removeDatabase() with a connection name to remove a connection.
408 QSqlDatabase outputs a warning if you try to remove a connection
409 referenced by other QSqlDatabase objects. Use contains() to see if
410 a given connection name is in the list of connections.
412 Once a connection is established, you can call tables() to get the
413 list of tables in the database, call primaryIndex() to get a
414 table's primary index, and call record() to get meta-information
415 about a table's fields (e.g., field names).
417 \note QSqlDatabase::exec() is deprecated. Use QSqlQuery::exec()
420 If the driver supports transactions, use transaction() to start a
421 transaction, and commit() or rollback() to complete it. Use
422 \l{QSqlDriver::} {hasFeature()} to ask if the driver supports
423 transactions. \note When using transactions, you must start the
424 transaction before you create your query.
426 If an error occurrs, lastError() will return information about it.
428 Get the names of the available SQL drivers with drivers(). Check
429 for the presence of a particular driver with isDriverAvailable().
430 If you have created your own custom driver, you must register it
431 with registerSqlDriver().
433 \sa QSqlDriver, QSqlQuery, {QtSql Module}, {Threads and the SQL Module}
436 /*! \fn QSqlDatabase QSqlDatabase::addDatabase(const QString &type, const QString &connectionName)
439 Adds a database to the list of database connections using the
440 driver \a type and the connection name \a connectionName. If
441 there already exists a database connection called \a
442 connectionName, that connection is removed.
444 The database connection is referred to by \a connectionName. The
445 newly added database connection is returned.
447 If \a connectionName is not specified, the new connection becomes
448 the default connection for the application, and subsequent calls
449 to database() without the connection name argument will return the
450 default connection. If a \a connectionName is provided here, use
451 database(\a connectionName) to retrieve the connection.
453 \warning If you add a connection with the same name as an existing
454 connection, the new connection replaces the old one. If you call
455 this function more than once without specifying \a connectionName,
456 the default connection will be the one replaced.
458 Before using the connection, it must be initialized. e.g., call
459 some or all of setDatabaseName(), setUserName(), setPassword(),
460 setHostName(), setPort(), and setConnectOptions(), and, finally,
463 \sa database() removeDatabase() {Threads and the SQL Module}
465 QSqlDatabase
QSqlDatabase::addDatabase(const QString
&type
, const QString
&connectionName
)
467 QSqlDatabase
db(type
);
468 QSqlDatabasePrivate::addDatabase(db
, connectionName
);
475 Returns the database connection called \a connectionName. The
476 database connection must have been previously added with
477 addDatabase(). If \a open is true (the default) and the database
478 connection is not already open it is opened now. If no \a
479 connectionName is specified the default connection is used. If \a
480 connectionName does not exist in the list of databases, an invalid
481 connection is returned.
483 \sa isOpen() {Threads and the SQL Module}
486 QSqlDatabase
QSqlDatabase::database(const QString
& connectionName
, bool open
)
488 return QSqlDatabasePrivate::database(connectionName
, open
);
494 Removes the database connection \a connectionName from the list of
495 database connections.
497 \warning There should be no open queries on the database
498 connection when this function is called, otherwise a resource leak
503 \snippet doc/src/snippets/code/src_sql_kernel_qsqldatabase.cpp 0
505 The correct way to do it:
507 \snippet doc/src/snippets/code/src_sql_kernel_qsqldatabase.cpp 1
509 To remove the default connection, which may have been created with a
510 call to addDatabase() not specifying a connection name, you can
511 retrieve the default connection name by calling connectionName() on
512 the database returned by database(). Note that if a default database
513 hasn't been created an invalid database will be returned.
515 \sa database() connectionName() {Threads and the SQL Module}
518 void QSqlDatabase::removeDatabase(const QString
& connectionName
)
520 QSqlDatabasePrivate::removeDatabase(connectionName
);
524 Returns a list of all the available database drivers.
526 \sa registerSqlDriver()
529 QStringList
QSqlDatabase::drivers()
534 list
<< QLatin1String("QPSQL7");
535 list
<< QLatin1String("QPSQL");
538 list
<< QLatin1String("QMYSQL3");
539 list
<< QLatin1String("QMYSQL");
542 list
<< QLatin1String("QODBC3");
543 list
<< QLatin1String("QODBC");
546 list
<< QLatin1String("QOCI8");
547 list
<< QLatin1String("QOCI");
550 list
<< QLatin1String("QTDS7");
551 list
<< QLatin1String("QTDS");
554 list
<< QLatin1String("QDB2");
557 list
<< QLatin1String("QSQLITE");
559 #ifdef QT_SQL_SQLITE2
560 list
<< QLatin1String("QSQLITE2");
563 list
<< QLatin1String("QIBASE");
566 #if !defined(QT_NO_LIBRARY) && !defined(QT_NO_SETTINGS)
567 if (QFactoryLoader
*fl
= loader()) {
568 QStringList keys
= fl
->keys();
569 for (QStringList::const_iterator i
= keys
.constBegin(); i
!= keys
.constEnd(); ++i
) {
570 if (!list
.contains(*i
))
576 DriverDict dict
= QSqlDatabasePrivate::driverDict();
577 for (DriverDict::const_iterator i
= dict
.constBegin(); i
!= dict
.constEnd(); ++i
) {
578 if (!list
.contains(i
.key()))
586 This function registers a new SQL driver called \a name, within
587 the SQL framework. This is useful if you have a custom SQL driver
588 and don't want to compile it as a plugin.
591 \snippet doc/src/snippets/code/src_sql_kernel_qsqldatabase.cpp 2
593 QSqlDatabase takes ownership of the \a creator pointer, so you
594 mustn't delete it yourself.
598 void QSqlDatabase::registerSqlDriver(const QString
& name
, QSqlDriverCreatorBase
*creator
)
600 delete QSqlDatabasePrivate::driverDict().take(name
);
602 QSqlDatabasePrivate::driverDict().insert(name
, creator
);
608 Returns true if the list of database connections contains \a
609 connectionName; otherwise returns false.
611 \sa connectionNames(), database(), {Threads and the SQL Module}
614 bool QSqlDatabase::contains(const QString
& connectionName
)
616 return dbDict()->contains_ts(connectionName
);
622 Returns a list containing the names of all connections.
624 \sa contains(), database(), {Threads and the SQL Module}
626 QStringList
QSqlDatabase::connectionNames()
628 return dbDict()->keys_ts();
634 Creates a QSqlDatabase connection that uses the driver referred
635 to by \a type. If the \a type is not recognized, the database
636 connection will have no functionality.
638 The currently available driver types are:
641 \header \i Driver Type \i Description
642 \row \i QDB2 \i IBM DB2
643 \row \i QIBASE \i Borland InterBase Driver
644 \row \i QMYSQL \i MySQL Driver
645 \row \i QOCI \i Oracle Call Interface Driver
646 \row \i QODBC \i ODBC Driver (includes Microsoft SQL Server)
647 \row \i QPSQL \i PostgreSQL Driver
648 \row \i QSQLITE \i SQLite version 3 or above
649 \row \i QSQLITE2 \i SQLite version 2
650 \row \i QTDS \i Sybase Adaptive Server
653 Additional third party drivers, including your own custom
654 drivers, can be loaded dynamically.
656 \sa {SQL Database Drivers}, registerSqlDriver(), drivers()
659 QSqlDatabase::QSqlDatabase(const QString
&type
)
661 d
= new QSqlDatabasePrivate();
668 Creates a database connection using the given \a driver.
671 QSqlDatabase::QSqlDatabase(QSqlDriver
*driver
)
673 d
= new QSqlDatabasePrivate(driver
);
677 Creates an empty, invalid QSqlDatabase object. Use addDatabase(),
678 removeDatabase(), and database() to get valid QSqlDatabase
681 QSqlDatabase::QSqlDatabase()
683 d
= QSqlDatabasePrivate::shared_null();
688 Creates a copy of \a other.
690 QSqlDatabase::QSqlDatabase(const QSqlDatabase
&other
)
697 Assigns \a other to this object.
699 QSqlDatabase
&QSqlDatabase::operator=(const QSqlDatabase
&other
)
701 qAtomicAssign(d
, other
.d
);
708 Create the actual driver instance \a type.
711 void QSqlDatabasePrivate::init(const QString
&type
)
717 if (type
== QLatin1String("QPSQL") || type
== QLatin1String("QPSQL7"))
718 driver
= new QPSQLDriver();
721 if (type
== QLatin1String("QMYSQL") || type
== QLatin1String("QMYSQL3"))
722 driver
= new QMYSQLDriver();
725 if (type
== QLatin1String("QODBC") || type
== QLatin1String("QODBC3"))
726 driver
= new QODBCDriver();
729 if (type
== QLatin1String("QOCI") || type
== QLatin1String("QOCI8"))
730 driver
= new QOCIDriver();
733 if (type
== QLatin1String("QTDS") || type
== QLatin1String("QTDS7"))
734 driver
= new QTDSDriver();
737 if (type
== QLatin1String("QDB2"))
738 driver
= new QDB2Driver();
741 if (type
== QLatin1String("QSQLITE"))
742 driver
= new QSQLiteDriver();
744 #ifdef QT_SQL_SQLITE2
745 if (type
== QLatin1String("QSQLITE2"))
746 driver
= new QSQLite2Driver();
749 if (type
== QLatin1String("QIBASE"))
750 driver
= new QIBaseDriver();
755 DriverDict dict
= QSqlDatabasePrivate::driverDict();
756 for (DriverDict::const_iterator it
= dict
.constBegin();
757 it
!= dict
.constEnd() && !driver
; ++it
) {
758 if (type
== it
.key()) {
759 driver
= ((QSqlDriverCreatorBase
*)(*it
))->createObject();
764 #if !defined(QT_NO_LIBRARY) && !defined(QT_NO_SETTINGS)
765 if (!driver
&& loader()) {
766 if (QSqlDriverFactoryInterface
*factory
= qobject_cast
<QSqlDriverFactoryInterface
*>(loader()->instance(type
)))
767 driver
= factory
->create(type
);
769 #endif // QT_NO_LIBRARY
772 qWarning("QSqlDatabase: %s driver not loaded", type
.toLatin1().data());
773 qWarning("QSqlDatabase: available drivers: %s",
774 QSqlDatabase::drivers().join(QLatin1String(" ")).toLatin1().data());
775 if (QCoreApplication::instance() == 0)
776 qWarning("QSqlDatabase: an instance of QCoreApplication is required for loading driver plugins");
777 driver
= shared_null()->driver
;
782 Destroys the object and frees any allocated resources.
784 If this is the last QSqlDatabase object that uses a certain
785 database connection, the is automatically closed.
790 QSqlDatabase::~QSqlDatabase()
792 if (!d
->ref
.deref()) {
799 Executes a SQL statement on the database and returns a QSqlQuery
800 object. Use lastError() to retrieve error information. If \a
801 query is empty, an empty, invalid query is returned and
802 lastError() is not affected.
804 \sa QSqlQuery, lastError()
807 QSqlQuery
QSqlDatabase::exec(const QString
& query
) const
809 QSqlQuery
r(d
->driver
->createResult());
810 if (!query
.isEmpty()) {
812 d
->driver
->setLastError(r
.lastError());
818 Opens the database connection using the current connection
819 values. Returns true on success; otherwise returns false. Error
820 information can be retrieved using lastError().
822 \sa lastError() setDatabaseName() setUserName() setPassword()
823 \sa setHostName() setPort() setConnectOptions()
826 bool QSqlDatabase::open()
828 return d
->driver
->open(d
->dbname
, d
->uname
, d
->pword
, d
->hname
,
829 d
->port
, d
->connOptions
);
835 Opens the database connection using the given \a user name and \a
836 password. Returns true on success; otherwise returns false. Error
837 information can be retrieved using the lastError() function.
839 This function does not store the password it is given. Instead,
840 the password is passed directly to the driver for opening the
841 connection and it is then discarded.
846 bool QSqlDatabase::open(const QString
& user
, const QString
& password
)
849 return d
->driver
->open(d
->dbname
, user
, password
, d
->hname
,
850 d
->port
, d
->connOptions
);
854 Closes the database connection, freeing any resources acquired, and
855 invalidating any existing QSqlQuery objects that are used with the
858 This will also affect copies of this QSqlDatabase object.
863 void QSqlDatabase::close()
869 Returns true if the database connection is currently open;
870 otherwise returns false.
873 bool QSqlDatabase::isOpen() const
875 return d
->driver
->isOpen();
879 Returns true if there was an error opening the database
880 connection; otherwise returns false. Error information can be
881 retrieved using the lastError() function.
884 bool QSqlDatabase::isOpenError() const
886 return d
->driver
->isOpenError();
890 Begins a transaction on the database if the driver supports
891 transactions. Returns \c{true} if the operation succeeded.
892 Otherwise it returns \c{false}.
894 \sa QSqlDriver::hasFeature(), commit(), rollback()
896 bool QSqlDatabase::transaction()
898 if (!d
->driver
->hasFeature(QSqlDriver::Transactions
))
900 return d
->driver
->beginTransaction();
904 Commits a transaction to the database if the driver supports
905 transactions and a transaction() has been started. Returns \c{true}
906 if the operation succeeded. Otherwise it returns \c{false}.
908 \note For some databases, the commit will fail and return \c{false}
909 if there is an \l{QSqlQuery::isActive()} {active query} using the
910 database for a \c{SELECT}. Make the query \l{QSqlQuery::isActive()}
911 {inactive} before doing the commit.
913 Call lastError() to get information about errors.
915 \sa QSqlQuery::isActive() QSqlDriver::hasFeature() rollback()
917 bool QSqlDatabase::commit()
919 if (!d
->driver
->hasFeature(QSqlDriver::Transactions
))
921 return d
->driver
->commitTransaction();
925 Rolls back a transaction on the database, if the driver supports
926 transactions and a transaction() has been started. Returns \c{true}
927 if the operation succeeded. Otherwise it returns \c{false}.
929 \note For some databases, the rollback will fail and return
930 \c{false} if there is an \l{QSqlQuery::isActive()} {active query}
931 using the database for a \c{SELECT}. Make the query
932 \l{QSqlQuery::isActive()} {inactive} before doing the rollback.
934 Call lastError() to get information about errors.
936 \sa QSqlQuery::isActive() QSqlDriver::hasFeature() commit()
938 bool QSqlDatabase::rollback()
940 if (!d
->driver
->hasFeature(QSqlDriver::Transactions
))
942 return d
->driver
->rollbackTransaction();
946 Sets the connection's database name to \a name. To have effect,
947 the database name must be set \e{before} the connection is
948 \l{open()} {opened}. Alternatively, you can close() the
949 connection, set the database name, and call open() again. \note
950 The \e{database name} is not the \e{connection name}. The
951 connection name must be passed to addDatabase() at connection
954 For the QOCI (Oracle) driver, the database name is the TNS
957 For the QODBC driver, the \a name can either be a DSN, a DSN
958 filename (in which case the file must have a \c .dsn extension),
959 or a connection string.
961 For example, Microsoft Access users can use the following
962 connection string to open an \c .mdb file directly, instead of
963 having to create a DSN entry in the ODBC manager:
965 \snippet doc/src/snippets/code/src_sql_kernel_qsqldatabase.cpp 3
967 There is no default value.
969 \sa databaseName() setUserName() setPassword() setHostName()
970 \sa setPort() setConnectOptions() open()
973 void QSqlDatabase::setDatabaseName(const QString
& name
)
980 Sets the connection's user name to \a name. To have effect, the
981 user name must be set \e{before} the connection is \l{open()}
982 {opened}. Alternatively, you can close() the connection, set the
983 user name, and call open() again.
985 There is no default value.
987 \sa userName() setDatabaseName() setPassword() setHostName()
988 \sa setPort() setConnectOptions() open()
991 void QSqlDatabase::setUserName(const QString
& name
)
998 Sets the connection's password to \a password. To have effect, the
999 password must be set \e{before} the connection is \l{open()}
1000 {opened}. Alternatively, you can close() the connection, set the
1001 password, and call open() again.
1003 There is no default value.
1005 \warning This function stores the password in plain text within
1006 Qt. Use the open() call that takes a password as parameter to
1007 avoid this behavior.
1009 \sa password() setUserName() setDatabaseName() setHostName()
1010 \sa setPort() setConnectOptions() open()
1013 void QSqlDatabase::setPassword(const QString
& password
)
1016 d
->pword
= password
;
1020 Sets the connection's host name to \a host. To have effect, the
1021 host name must be set \e{before} the connection is \l{open()}
1022 {opened}. Alternatively, you can close() the connection, set the
1023 host name, and call open() again.
1025 There is no default value.
1027 \sa hostName() setUserName() setPassword() setDatabaseName()
1028 \sa setPort() setConnectOptions() open()
1031 void QSqlDatabase::setHostName(const QString
& host
)
1038 Sets the connection's port number to \a port. To have effect, the
1039 port number must be set \e{before} the connection is \l{open()}
1040 {opened}. Alternatively, you can close() the connection, set the
1041 port number, and call open() again..
1043 There is no default value.
1045 \sa port() setUserName() setPassword() setHostName()
1046 \sa setDatabaseName() setConnectOptions() open()
1049 void QSqlDatabase::setPort(int port
)
1056 Returns the connection's database name, which may be empty.
1057 \note The database name is not the connection name.
1059 \sa setDatabaseName()
1061 QString
QSqlDatabase::databaseName() const
1067 Returns the connection's user name; it may be empty.
1071 QString
QSqlDatabase::userName() const
1077 Returns the connection's password. If the password was not set
1078 with setPassword(), and if the password was given in the open()
1079 call, or if no password was used, an empty string is returned.
1081 QString
QSqlDatabase::password() const
1087 Returns the connection's host name; it may be empty.
1091 QString
QSqlDatabase::hostName() const
1097 Returns the connection's driver name.
1099 \sa addDatabase(), driver()
1101 QString
QSqlDatabase::driverName() const
1107 Returns the connection's port number. The value is undefined if
1108 the port number has not been set.
1112 int QSqlDatabase::port() const
1118 Returns the database driver used to access the database
1121 \sa addDatabase() drivers()
1124 QSqlDriver
* QSqlDatabase::driver() const
1130 Returns information about the last error that occurred on the
1133 Failures that occur in conjunction with an individual query are
1134 reported by QSqlQuery::lastError().
1136 \sa QSqlError, QSqlQuery::lastError()
1139 QSqlError
QSqlDatabase::lastError() const
1141 return d
->driver
->lastError();
1146 Returns a list of the database's tables, system tables and views,
1147 as specified by the parameter \a type.
1149 \sa primaryIndex(), record()
1152 QStringList
QSqlDatabase::tables(QSql::TableType type
) const
1154 return d
->driver
->tables(type
);
1158 Returns the primary index for table \a tablename. If no primary
1159 index exists an empty QSqlIndex is returned.
1161 \sa tables(), record()
1164 QSqlIndex
QSqlDatabase::primaryIndex(const QString
& tablename
) const
1166 return d
->driver
->primaryIndex(tablename
);
1171 Returns a QSqlRecord populated with the names of all the fields in
1172 the table (or view) called \a tablename. The order in which the
1173 fields appear in the record is undefined. If no such table (or
1174 view) exists, an empty record is returned.
1177 QSqlRecord
QSqlDatabase::record(const QString
& tablename
) const
1179 return d
->driver
->record(tablename
);
1184 Sets database-specific \a options. This must be done before the
1185 connection is opened or it has no effect (or you can close() the
1186 connection, call this function and open() the connection again).
1188 The format of the \a options string is a semicolon separated list
1189 of option names or option=value pairs. The options depend on the
1190 database client used:
1193 \header \i ODBC \i MySQL \i PostgreSQL
1198 \i SQL_ATTR_ACCESS_MODE
1199 \i SQL_ATTR_LOGIN_TIMEOUT
1200 \i SQL_ATTR_CONNECTION_TIMEOUT
1201 \i SQL_ATTR_CURRENT_CATALOG
1202 \i SQL_ATTR_METADATA_ID
1203 \i SQL_ATTR_PACKET_SIZE
1204 \i SQL_ATTR_TRACEFILE
1206 \i SQL_ATTR_CONNECTION_POOLING
1207 \i SQL_ATTR_ODBC_VERSION
1213 \i CLIENT_FOUND_ROWS
1214 \i CLIENT_IGNORE_SPACE
1218 \i CLIENT_INTERACTIVE
1231 \header \i DB2 \i OCI \i TDS
1236 \i SQL_ATTR_ACCESS_MODE
1237 \i SQL_ATTR_LOGIN_TIMEOUT
1242 \i OCI_ATTR_PREFETCH_ROWS
1243 \i OCI_ATTR_PREFETCH_MEMORY
1249 \header \i SQLite \i Interbase
1254 \i QSQLITE_BUSY_TIMEOUT
1260 \i ISC_DPB_SQL_ROLE_NAME
1266 \snippet doc/src/snippets/code/src_sql_kernel_qsqldatabase.cpp 4
1268 Refer to the client library documentation for more information
1269 about the different options.
1271 \sa connectOptions()
1274 void QSqlDatabase::setConnectOptions(const QString
&options
)
1277 d
->connOptions
= options
;
1281 Returns the connection options string used for this connection.
1282 The string may be empty.
1284 \sa setConnectOptions()
1286 QString
QSqlDatabase::connectOptions() const
1288 return d
->connOptions
;
1292 Returns true if a driver called \a name is available; otherwise
1298 bool QSqlDatabase::isDriverAvailable(const QString
& name
)
1300 return drivers().contains(name
);
1303 /*! \fn QSqlDatabase QSqlDatabase::addDatabase(QSqlDriver* driver, const QString& connectionName)
1305 This overload is useful when you want to create a database
1306 connection with a \l{QSqlDriver} {driver} you instantiated
1307 yourself. It might be your own database driver, or you might just
1308 need to instantiate one of the Qt drivers yourself. If you do
1309 this, it is recommended that you include the driver code in your
1310 application. For example, you can create a PostgreSQL connection
1311 with your own QPSQL driver like this:
1313 \snippet doc/src/snippets/code/src_sql_kernel_qsqldatabase.cpp 5
1315 \snippet doc/src/snippets/code/src_sql_kernel_qsqldatabase.cpp 6
1317 The above code sets up a PostgreSQL connection and instantiates a
1318 QPSQLDriver object. Next, addDatabase() is called to add the
1319 connection to the known connections so that it can be used by the
1320 Qt SQL classes. When a driver is instantiated with a connection
1321 handle (or set of handles), Qt assumes that you have already
1322 opened the database connection.
1324 \note We assume that \c qtdir is the directory where Qt is
1325 installed. This will pull in the code that is needed to use the
1326 PostgreSQL client library and to instantiate a QPSQLDriver object,
1327 assuming that you have the PostgreSQL headers somewhere in your
1328 include search path.
1330 Remember that you must link your application against the database
1331 client library. Make sure the client library is in your linker's
1332 search path, and add lines like these to your \c{.pro} file:
1334 \snippet doc/src/snippets/code/src_sql_kernel_qsqldatabase.cpp 7
1336 The method described works for all the supplied drivers. The only
1337 difference will be in the driver constructor arguments. Here is a
1338 table of the drivers included with Qt, their source code files,
1339 and their constructor arguments:
1342 \header \i Driver \i Class name \i Constructor arguments \i File to include
1346 \i PGconn *connection
1351 \i MYSQL *connection
1352 \i \c qsql_mysql.cpp
1356 \i OCIEnv *environment, OCISvcCtx *serviceContext
1361 \i SQLHANDLE environment, SQLHANDLE connection
1366 \i SQLHANDLE environment, SQLHANDLE connection
1371 \i LOGINREC *loginRecord, DBPROCESS *dbProcess, const QString &hostName
1376 \i sqlite *connection
1377 \i \c qsql_sqlite.cpp
1381 \i isc_db_handle connection
1382 \i \c qsql_ibase.cpp
1385 The host name (or service name) is needed when constructing the
1386 QTDSDriver for creating new connections for internal queries. This
1387 is to prevent blocking when several QSqlQuery objects are used
1390 \warning Adding a database connection with the same connection
1391 name as an existing connection, causes the existing connection to
1392 be replaced by the new one.
1394 \warning The SQL framework takes ownership of the \a driver. It
1395 must not be deleted. To remove the connection, use
1400 QSqlDatabase
QSqlDatabase::addDatabase(QSqlDriver
* driver
, const QString
& connectionName
)
1402 QSqlDatabase
db(driver
);
1403 QSqlDatabasePrivate::addDatabase(db
, connectionName
);
1408 Returns true if the QSqlDatabase has a valid driver.
1411 \snippet doc/src/snippets/code/src_sql_kernel_qsqldatabase.cpp 8
1413 bool QSqlDatabase::isValid() const
1415 return d
->driver
&& d
->driver
!= d
->shared_null()->driver
;
1420 Use query.record() instead.
1422 QSqlRecord
QSqlDatabase::record(const QSqlQuery
& query
) const
1423 { return query
.record(); }
1426 Use query.record() instead.
1428 QSqlRecord
QSqlDatabase::recordInfo(const QSqlQuery
& query
) const
1429 { return query
.record(); }
1432 \fn QSqlRecord QSqlDatabase::recordInfo(const QString& tablename) const
1434 Use record() instead.
1439 Clones the database connection \a other and and stores it as \a
1440 connectionName. All the settings from the original database, e.g.
1441 databaseName(), hostName(), etc., are copied across. Does nothing
1442 if \a other is an invalid database. Returns the newly created
1443 database connection.
1445 \note The new connection has not been opened. Before using the new
1446 connection, you must call open().
1448 QSqlDatabase
QSqlDatabase::cloneDatabase(const QSqlDatabase
&other
, const QString
&connectionName
)
1450 if (!other
.isValid())
1451 return QSqlDatabase();
1453 QSqlDatabase
db(other
.driverName());
1454 db
.d
->copy(other
.d
);
1455 QSqlDatabasePrivate::addDatabase(db
, connectionName
);
1462 Returns the connection name, which may be empty. \note The
1463 connection name is not the \l{databaseName()} {database name}.
1467 QString
QSqlDatabase::connectionName() const
1472 #ifndef QT_NO_DEBUG_STREAM
1473 QDebug
operator<<(QDebug dbg
, const QSqlDatabase
&d
)
1476 dbg
.nospace() << "QSqlDatabase(invalid)";
1480 dbg
.nospace() << "QSqlDatabase(driver=\"" << d
.driverName() << "\", database=\""
1481 << d
.databaseName() << "\", host=\"" << d
.hostName() << "\", port=" << d
.port()
1482 << ", user=\"" << d
.userName() << "\", open=" << d
.isOpen() << ")";