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$
10 ** No Commercial Usage
11 ** This file contains pre-release code and may not be distributed.
12 ** You may use this file in accordance with the terms and conditions
13 ** contained in the Technology Preview License Agreement accompanying
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 ** If you have questions regarding the use of this file, please contact
29 ** 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(QSqlDatabase
*d
, QSqlDriver
*dr
= 0):
139 precisionPolicy
= driver
->numericalPrecisionPolicy();
141 precisionPolicy
= QSql::LowPrecisionDouble
;
143 QSqlDatabasePrivate(const QSqlDatabasePrivate
&other
);
144 ~QSqlDatabasePrivate();
145 void init(const QString
& type
);
146 void copy(const QSqlDatabasePrivate
*other
);
160 QSql::NumericalPrecisionPolicy precisionPolicy
;
162 static QSqlDatabasePrivate
*shared_null();
163 static QSqlDatabase
database(const QString
& name
, bool open
);
164 static void addDatabase(const QSqlDatabase
&db
, const QString
& name
);
165 static void removeDatabase(const QString
& name
);
166 static void invalidateDb(const QSqlDatabase
&db
, const QString
&name
);
167 static DriverDict
&driverDict();
168 static void cleanConnections();
171 QSqlDatabasePrivate::QSqlDatabasePrivate(const QSqlDatabasePrivate
&other
)
175 dbname
= other
.dbname
;
179 drvName
= other
.drvName
;
181 connOptions
= other
.connOptions
;
182 driver
= other
.driver
;
183 precisionPolicy
= other
.precisionPolicy
;
186 QSqlDatabasePrivate::~QSqlDatabasePrivate()
188 if (driver
!= shared_null()->driver
)
192 void QSqlDatabasePrivate::cleanConnections()
194 QConnectionDict
*dict
= dbDict();
196 QWriteLocker
locker(&dict
->lock
);
198 QConnectionDict::iterator it
= dict
->begin();
199 while (it
!= dict
->end()) {
200 invalidateDb(it
.value(), it
.key());
206 static bool qDriverDictInit
= false;
207 static void cleanDriverDict()
209 qDeleteAll(QSqlDatabasePrivate::driverDict());
210 QSqlDatabasePrivate::driverDict().clear();
211 QSqlDatabasePrivate::cleanConnections();
212 qDriverDictInit
= false;
215 DriverDict
&QSqlDatabasePrivate::driverDict()
217 static DriverDict dict
;
218 if (!qDriverDictInit
) {
219 qDriverDictInit
= true;
220 qAddPostRoutine(cleanDriverDict
);
225 QSqlDatabasePrivate
*QSqlDatabasePrivate::shared_null()
227 static QSqlNullDriver dr
;
228 static QSqlDatabasePrivate
n(NULL
, &dr
);
232 void QSqlDatabasePrivate::invalidateDb(const QSqlDatabase
&db
, const QString
&name
)
234 if (db
.d
->ref
!= 1) {
235 qWarning("QSqlDatabasePrivate::removeDatabase: connection '%s' is still in use, "
236 "all queries will cease to work.", name
.toLocal8Bit().constData());
238 db
.d
->connName
.clear();
242 void QSqlDatabasePrivate::removeDatabase(const QString
&name
)
244 QConnectionDict
*dict
= dbDict();
246 QWriteLocker
locker(&dict
->lock
);
248 if (!dict
->contains(name
))
251 invalidateDb(dict
->take(name
), name
);
254 void QSqlDatabasePrivate::addDatabase(const QSqlDatabase
&db
, const QString
&name
)
256 QConnectionDict
*dict
= dbDict();
258 QWriteLocker
locker(&dict
->lock
);
260 if (dict
->contains(name
)) {
261 invalidateDb(dict
->take(name
), name
);
262 qWarning("QSqlDatabasePrivate::addDatabase: duplicate connection name '%s', old "
263 "connection removed.", name
.toLocal8Bit().data());
265 dict
->insert(name
, db
);
266 db
.d
->connName
= name
;
271 QSqlDatabase
QSqlDatabasePrivate::database(const QString
& name
, bool open
)
273 const QConnectionDict
*dict
= dbDict();
276 dict
->lock
.lockForRead();
277 QSqlDatabase db
= dict
->value(name
);
279 if (db
.isValid() && !db
.isOpen() && open
) {
281 qWarning() << "QSqlDatabasePrivate::database: unable to open database:" << db
.lastError().text();
289 Copies the connection data from \a other.
291 void QSqlDatabasePrivate::copy(const QSqlDatabasePrivate
*other
)
294 dbname
= other
->dbname
;
295 uname
= other
->uname
;
296 pword
= other
->pword
;
297 hname
= other
->hname
;
298 drvName
= other
->drvName
;
300 connOptions
= other
->connOptions
;
301 precisionPolicy
= other
->precisionPolicy
;
304 void QSqlDatabasePrivate::disable()
306 if (driver
!= shared_null()->driver
) {
308 driver
= shared_null()->driver
;
313 \class QSqlDriverCreatorBase
314 \brief The QSqlDriverCreatorBase class is the base class for
315 SQL driver factories.
320 Reimplement createObject() to return an instance of the specific
321 QSqlDriver subclass that you want to provide.
323 See QSqlDatabase::registerSqlDriver() for details.
325 \sa QSqlDriverCreator
329 \fn QSqlDriverCreatorBase::~QSqlDriverCreatorBase()
331 Destroys the SQL driver creator object.
335 \fn QSqlDriver *QSqlDriverCreatorBase::createObject() const
337 Reimplement this function to returns a new instance of a
342 \class QSqlDriverCreator
343 \brief The QSqlDriverCreator class is a template class that
344 provides a SQL driver factory for a specific driver type.
349 QSqlDriverCreator<T> instantiates objects of type T, where T is a
352 See QSqlDatabase::registerSqlDriver() for details.
356 \fn QSqlDriver *QSqlDriverCreator::createObject() const
362 \brief The QSqlDatabase class represents a connection to
369 The QSqlDatabase class provides an interface for accessing a
370 database through a connection. An instance of QSqlDatabase
371 represents the connection. The connection provides access to the
372 database via one of the \l{SQL Database Drivers#Supported
373 Databases} {supported database drivers}, which are derived from
374 QSqlDriver. Alternatively, you can subclass your own database
375 driver from QSqlDriver. See \l{How to Write Your Own Database
376 Driver} for more information.
378 Create a connection (i.e., an instance of QSqlDatabase) by calling
379 one of the static addDatabase() functions, where you specify
380 \l{SQL Database Drivers#Supported Databases} {the driver or type
381 of driver} to use (i.e., what kind of database will you access?)
382 and a connection name. A connection is known by its own name,
383 \e{not} by the name of the database it connects to. You can have
384 multiple connections to one database. QSqlDatabase also supports
385 the concept of a \e{default} connection, which is the unnamed
386 connection. To create the default connection, don't pass the
387 connection name argument when you call addDatabase().
388 Subsequently, when you call any static member function that takes
389 the connection name argument, if you don't pass the connection
390 name argument, the default connection is assumed. The following
391 snippet shows how to create and open a default connection to a
394 \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 0
396 Once the QSqlDatabase object has been created, set the connection
397 parameters with setDatabaseName(), setUserName(), setPassword(),
398 setHostName(), setPort(), and setConnectOptions(). Then call
399 open() to activate the physical connection to the database. The
400 connection is not usable until you open it.
402 The connection defined above will be the \e{default} connection,
403 because we didn't give a connection name to \l{QSqlDatabase::}
404 {addDatabase()}. Subsequently, you can get the default connection
405 by calling database() without the connection name argument:
407 \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 1
409 QSqlDatabase is a value class. Changes made to a database
410 connection via one instance of QSqlDatabase will affect other
411 instances of QSqlDatabase that represent the same connection. Use
412 cloneDatabase() to create an independent database connection based
415 If you create multiple database connections, specify a unique
416 connection name for each one, when you call addDatabase(). Use
417 database() with a connection name to get that connection. Use
418 removeDatabase() with a connection name to remove a connection.
419 QSqlDatabase outputs a warning if you try to remove a connection
420 referenced by other QSqlDatabase objects. Use contains() to see if
421 a given connection name is in the list of connections.
423 Once a connection is established, you can call tables() to get the
424 list of tables in the database, call primaryIndex() to get a
425 table's primary index, and call record() to get meta-information
426 about a table's fields (e.g., field names).
428 \note QSqlDatabase::exec() is deprecated. Use QSqlQuery::exec()
431 If the driver supports transactions, use transaction() to start a
432 transaction, and commit() or rollback() to complete it. Use
433 \l{QSqlDriver::} {hasFeature()} to ask if the driver supports
434 transactions. \note When using transactions, you must start the
435 transaction before you create your query.
437 If an error occurrs, lastError() will return information about it.
439 Get the names of the available SQL drivers with drivers(). Check
440 for the presence of a particular driver with isDriverAvailable().
441 If you have created your own custom driver, you must register it
442 with registerSqlDriver().
444 \sa QSqlDriver, QSqlQuery, {QtSql Module}, {Threads and the SQL Module}
447 /*! \fn QSqlDatabase QSqlDatabase::addDatabase(const QString &type, const QString &connectionName)
450 Adds a database to the list of database connections using the
451 driver \a type and the connection name \a connectionName. If
452 there already exists a database connection called \a
453 connectionName, that connection is removed.
455 The database connection is referred to by \a connectionName. The
456 newly added database connection is returned.
458 If \a type is not available or could not be loaded, isValid() returns false.
460 If \a connectionName is not specified, the new connection becomes
461 the default connection for the application, and subsequent calls
462 to database() without the connection name argument will return the
463 default connection. If a \a connectionName is provided here, use
464 database(\a connectionName) to retrieve the connection.
466 \warning If you add a connection with the same name as an existing
467 connection, the new connection replaces the old one. If you call
468 this function more than once without specifying \a connectionName,
469 the default connection will be the one replaced.
471 Before using the connection, it must be initialized. e.g., call
472 some or all of setDatabaseName(), setUserName(), setPassword(),
473 setHostName(), setPort(), and setConnectOptions(), and, finally,
476 \sa database() removeDatabase() {Threads and the SQL Module}
478 QSqlDatabase
QSqlDatabase::addDatabase(const QString
&type
, const QString
&connectionName
)
480 QSqlDatabase
db(type
);
481 QSqlDatabasePrivate::addDatabase(db
, connectionName
);
488 Returns the database connection called \a connectionName. The
489 database connection must have been previously added with
490 addDatabase(). If \a open is true (the default) and the database
491 connection is not already open it is opened now. If no \a
492 connectionName is specified the default connection is used. If \a
493 connectionName does not exist in the list of databases, an invalid
494 connection is returned.
496 \sa isOpen() {Threads and the SQL Module}
499 QSqlDatabase
QSqlDatabase::database(const QString
& connectionName
, bool open
)
501 return QSqlDatabasePrivate::database(connectionName
, open
);
507 Removes the database connection \a connectionName from the list of
508 database connections.
510 \warning There should be no open queries on the database
511 connection when this function is called, otherwise a resource leak
516 \snippet doc/src/snippets/code/src_sql_kernel_qsqldatabase.cpp 0
518 The correct way to do it:
520 \snippet doc/src/snippets/code/src_sql_kernel_qsqldatabase.cpp 1
522 To remove the default connection, which may have been created with a
523 call to addDatabase() not specifying a connection name, you can
524 retrieve the default connection name by calling connectionName() on
525 the database returned by database(). Note that if a default database
526 hasn't been created an invalid database will be returned.
528 \sa database() connectionName() {Threads and the SQL Module}
531 void QSqlDatabase::removeDatabase(const QString
& connectionName
)
533 QSqlDatabasePrivate::removeDatabase(connectionName
);
537 Returns a list of all the available database drivers.
539 \sa registerSqlDriver()
542 QStringList
QSqlDatabase::drivers()
547 list
<< QLatin1String("QPSQL7");
548 list
<< QLatin1String("QPSQL");
551 list
<< QLatin1String("QMYSQL3");
552 list
<< QLatin1String("QMYSQL");
555 list
<< QLatin1String("QODBC3");
556 list
<< QLatin1String("QODBC");
559 list
<< QLatin1String("QOCI8");
560 list
<< QLatin1String("QOCI");
563 list
<< QLatin1String("QTDS7");
564 list
<< QLatin1String("QTDS");
567 list
<< QLatin1String("QDB2");
570 list
<< QLatin1String("QSQLITE");
572 #ifdef QT_SQL_SQLITE2
573 list
<< QLatin1String("QSQLITE2");
576 list
<< QLatin1String("QIBASE");
579 #if !defined(QT_NO_LIBRARY) && !defined(QT_NO_SETTINGS)
580 if (QFactoryLoader
*fl
= loader()) {
581 QStringList keys
= fl
->keys();
582 for (QStringList::const_iterator i
= keys
.constBegin(); i
!= keys
.constEnd(); ++i
) {
583 if (!list
.contains(*i
))
589 DriverDict dict
= QSqlDatabasePrivate::driverDict();
590 for (DriverDict::const_iterator i
= dict
.constBegin(); i
!= dict
.constEnd(); ++i
) {
591 if (!list
.contains(i
.key()))
599 This function registers a new SQL driver called \a name, within
600 the SQL framework. This is useful if you have a custom SQL driver
601 and don't want to compile it as a plugin.
604 \snippet doc/src/snippets/code/src_sql_kernel_qsqldatabase.cpp 2
606 QSqlDatabase takes ownership of the \a creator pointer, so you
607 mustn't delete it yourself.
611 void QSqlDatabase::registerSqlDriver(const QString
& name
, QSqlDriverCreatorBase
*creator
)
613 delete QSqlDatabasePrivate::driverDict().take(name
);
615 QSqlDatabasePrivate::driverDict().insert(name
, creator
);
621 Returns true if the list of database connections contains \a
622 connectionName; otherwise returns false.
624 \sa connectionNames(), database(), {Threads and the SQL Module}
627 bool QSqlDatabase::contains(const QString
& connectionName
)
629 return dbDict()->contains_ts(connectionName
);
635 Returns a list containing the names of all connections.
637 \sa contains(), database(), {Threads and the SQL Module}
639 QStringList
QSqlDatabase::connectionNames()
641 return dbDict()->keys_ts();
647 Creates a QSqlDatabase connection that uses the driver referred
648 to by \a type. If the \a type is not recognized, the database
649 connection will have no functionality.
651 The currently available driver types are:
654 \header \i Driver Type \i Description
655 \row \i QDB2 \i IBM DB2
656 \row \i QIBASE \i Borland InterBase Driver
657 \row \i QMYSQL \i MySQL Driver
658 \row \i QOCI \i Oracle Call Interface Driver
659 \row \i QODBC \i ODBC Driver (includes Microsoft SQL Server)
660 \row \i QPSQL \i PostgreSQL Driver
661 \row \i QSQLITE \i SQLite version 3 or above
662 \row \i QSQLITE2 \i SQLite version 2
663 \row \i QTDS \i Sybase Adaptive Server
666 Additional third party drivers, including your own custom
667 drivers, can be loaded dynamically.
669 \sa {SQL Database Drivers}, registerSqlDriver(), drivers()
672 QSqlDatabase::QSqlDatabase(const QString
&type
)
674 d
= new QSqlDatabasePrivate(this);
681 Creates a database connection using the given \a driver.
684 QSqlDatabase::QSqlDatabase(QSqlDriver
*driver
)
686 d
= new QSqlDatabasePrivate(this, driver
);
690 Creates an empty, invalid QSqlDatabase object. Use addDatabase(),
691 removeDatabase(), and database() to get valid QSqlDatabase
694 QSqlDatabase::QSqlDatabase()
696 d
= QSqlDatabasePrivate::shared_null();
701 Creates a copy of \a other.
703 QSqlDatabase::QSqlDatabase(const QSqlDatabase
&other
)
710 Assigns \a other to this object.
712 QSqlDatabase
&QSqlDatabase::operator=(const QSqlDatabase
&other
)
714 qAtomicAssign(d
, other
.d
);
721 Create the actual driver instance \a type.
724 void QSqlDatabasePrivate::init(const QString
&type
)
730 if (type
== QLatin1String("QPSQL") || type
== QLatin1String("QPSQL7"))
731 driver
= new QPSQLDriver();
734 if (type
== QLatin1String("QMYSQL") || type
== QLatin1String("QMYSQL3"))
735 driver
= new QMYSQLDriver();
738 if (type
== QLatin1String("QODBC") || type
== QLatin1String("QODBC3"))
739 driver
= new QODBCDriver();
742 if (type
== QLatin1String("QOCI") || type
== QLatin1String("QOCI8"))
743 driver
= new QOCIDriver();
746 if (type
== QLatin1String("QTDS") || type
== QLatin1String("QTDS7"))
747 driver
= new QTDSDriver();
750 if (type
== QLatin1String("QDB2"))
751 driver
= new QDB2Driver();
754 if (type
== QLatin1String("QSQLITE"))
755 driver
= new QSQLiteDriver();
757 #ifdef QT_SQL_SQLITE2
758 if (type
== QLatin1String("QSQLITE2"))
759 driver
= new QSQLite2Driver();
762 if (type
== QLatin1String("QIBASE"))
763 driver
= new QIBaseDriver();
768 DriverDict dict
= QSqlDatabasePrivate::driverDict();
769 for (DriverDict::const_iterator it
= dict
.constBegin();
770 it
!= dict
.constEnd() && !driver
; ++it
) {
771 if (type
== it
.key()) {
772 driver
= ((QSqlDriverCreatorBase
*)(*it
))->createObject();
777 #if !defined(QT_NO_LIBRARY) && !defined(QT_NO_SETTINGS)
778 if (!driver
&& loader()) {
779 if (QSqlDriverFactoryInterface
*factory
= qobject_cast
<QSqlDriverFactoryInterface
*>(loader()->instance(type
)))
780 driver
= factory
->create(type
);
782 #endif // QT_NO_LIBRARY
785 qWarning("QSqlDatabase: %s driver not loaded", type
.toLatin1().data());
786 qWarning("QSqlDatabase: available drivers: %s",
787 QSqlDatabase::drivers().join(QLatin1String(" ")).toLatin1().data());
788 if (QCoreApplication::instance() == 0)
789 qWarning("QSqlDatabase: an instance of QCoreApplication is required for loading driver plugins");
790 driver
= shared_null()->driver
;
795 Destroys the object and frees any allocated resources.
797 If this is the last QSqlDatabase object that uses a certain
798 database connection, the is automatically closed.
803 QSqlDatabase::~QSqlDatabase()
805 if (!d
->ref
.deref()) {
812 Executes a SQL statement on the database and returns a QSqlQuery
813 object. Use lastError() to retrieve error information. If \a
814 query is empty, an empty, invalid query is returned and
815 lastError() is not affected.
817 \sa QSqlQuery, lastError()
820 QSqlQuery
QSqlDatabase::exec(const QString
& query
) const
822 QSqlQuery
r(d
->driver
->createResult());
823 if (!query
.isEmpty()) {
825 d
->driver
->setLastError(r
.lastError());
831 Opens the database connection using the current connection
832 values. Returns true on success; otherwise returns false. Error
833 information can be retrieved using lastError().
835 \sa lastError() setDatabaseName() setUserName() setPassword()
836 \sa setHostName() setPort() setConnectOptions()
839 bool QSqlDatabase::open()
841 return d
->driver
->open(d
->dbname
, d
->uname
, d
->pword
, d
->hname
,
842 d
->port
, d
->connOptions
);
848 Opens the database connection using the given \a user name and \a
849 password. Returns true on success; otherwise returns false. Error
850 information can be retrieved using the lastError() function.
852 This function does not store the password it is given. Instead,
853 the password is passed directly to the driver for opening the
854 connection and it is then discarded.
859 bool QSqlDatabase::open(const QString
& user
, const QString
& password
)
862 return d
->driver
->open(d
->dbname
, user
, password
, d
->hname
,
863 d
->port
, d
->connOptions
);
867 Closes the database connection, freeing any resources acquired, and
868 invalidating any existing QSqlQuery objects that are used with the
871 This will also affect copies of this QSqlDatabase object.
876 void QSqlDatabase::close()
882 Returns true if the database connection is currently open;
883 otherwise returns false.
886 bool QSqlDatabase::isOpen() const
888 return d
->driver
->isOpen();
892 Returns true if there was an error opening the database
893 connection; otherwise returns false. Error information can be
894 retrieved using the lastError() function.
897 bool QSqlDatabase::isOpenError() const
899 return d
->driver
->isOpenError();
903 Begins a transaction on the database if the driver supports
904 transactions. Returns \c{true} if the operation succeeded.
905 Otherwise it returns \c{false}.
907 \sa QSqlDriver::hasFeature(), commit(), rollback()
909 bool QSqlDatabase::transaction()
911 if (!d
->driver
->hasFeature(QSqlDriver::Transactions
))
913 return d
->driver
->beginTransaction();
917 Commits a transaction to the database if the driver supports
918 transactions and a transaction() has been started. Returns \c{true}
919 if the operation succeeded. Otherwise it returns \c{false}.
921 \note For some databases, the commit will fail and return \c{false}
922 if there is an \l{QSqlQuery::isActive()} {active query} using the
923 database for a \c{SELECT}. Make the query \l{QSqlQuery::isActive()}
924 {inactive} before doing the commit.
926 Call lastError() to get information about errors.
928 \sa QSqlQuery::isActive() QSqlDriver::hasFeature() rollback()
930 bool QSqlDatabase::commit()
932 if (!d
->driver
->hasFeature(QSqlDriver::Transactions
))
934 return d
->driver
->commitTransaction();
938 Rolls back a transaction on the database, if the driver supports
939 transactions and a transaction() has been started. Returns \c{true}
940 if the operation succeeded. Otherwise it returns \c{false}.
942 \note For some databases, the rollback will fail and return
943 \c{false} if there is an \l{QSqlQuery::isActive()} {active query}
944 using the database for a \c{SELECT}. Make the query
945 \l{QSqlQuery::isActive()} {inactive} before doing the rollback.
947 Call lastError() to get information about errors.
949 \sa QSqlQuery::isActive() QSqlDriver::hasFeature() commit()
951 bool QSqlDatabase::rollback()
953 if (!d
->driver
->hasFeature(QSqlDriver::Transactions
))
955 return d
->driver
->rollbackTransaction();
959 Sets the connection's database name to \a name. To have effect,
960 the database name must be set \e{before} the connection is
961 \l{open()} {opened}. Alternatively, you can close() the
962 connection, set the database name, and call open() again. \note
963 The \e{database name} is not the \e{connection name}. The
964 connection name must be passed to addDatabase() at connection
967 For the QOCI (Oracle) driver, the database name is the TNS
970 For the QODBC driver, the \a name can either be a DSN, a DSN
971 filename (in which case the file must have a \c .dsn extension),
972 or a connection string.
974 For example, Microsoft Access users can use the following
975 connection string to open an \c .mdb file directly, instead of
976 having to create a DSN entry in the ODBC manager:
978 \snippet doc/src/snippets/code/src_sql_kernel_qsqldatabase.cpp 3
980 There is no default value.
982 \sa databaseName() setUserName() setPassword() setHostName()
983 \sa setPort() setConnectOptions() open()
986 void QSqlDatabase::setDatabaseName(const QString
& name
)
993 Sets the connection's user name to \a name. To have effect, the
994 user name must be set \e{before} the connection is \l{open()}
995 {opened}. Alternatively, you can close() the connection, set the
996 user name, and call open() again.
998 There is no default value.
1000 \sa userName() setDatabaseName() setPassword() setHostName()
1001 \sa setPort() setConnectOptions() open()
1004 void QSqlDatabase::setUserName(const QString
& name
)
1011 Sets the connection's password to \a password. To have effect, the
1012 password must be set \e{before} the connection is \l{open()}
1013 {opened}. Alternatively, you can close() the connection, set the
1014 password, and call open() again.
1016 There is no default value.
1018 \warning This function stores the password in plain text within
1019 Qt. Use the open() call that takes a password as parameter to
1020 avoid this behavior.
1022 \sa password() setUserName() setDatabaseName() setHostName()
1023 \sa setPort() setConnectOptions() open()
1026 void QSqlDatabase::setPassword(const QString
& password
)
1029 d
->pword
= password
;
1033 Sets the connection's host name to \a host. To have effect, the
1034 host name must be set \e{before} the connection is \l{open()}
1035 {opened}. Alternatively, you can close() the connection, set the
1036 host name, and call open() again.
1038 There is no default value.
1040 \sa hostName() setUserName() setPassword() setDatabaseName()
1041 \sa setPort() setConnectOptions() open()
1044 void QSqlDatabase::setHostName(const QString
& host
)
1051 Sets the connection's port number to \a port. To have effect, the
1052 port number must be set \e{before} the connection is \l{open()}
1053 {opened}. Alternatively, you can close() the connection, set the
1054 port number, and call open() again..
1056 There is no default value.
1058 \sa port() setUserName() setPassword() setHostName()
1059 \sa setDatabaseName() setConnectOptions() open()
1062 void QSqlDatabase::setPort(int port
)
1069 Returns the connection's database name, which may be empty.
1070 \note The database name is not the connection name.
1072 \sa setDatabaseName()
1074 QString
QSqlDatabase::databaseName() const
1080 Returns the connection's user name; it may be empty.
1084 QString
QSqlDatabase::userName() const
1090 Returns the connection's password. If the password was not set
1091 with setPassword(), and if the password was given in the open()
1092 call, or if no password was used, an empty string is returned.
1094 QString
QSqlDatabase::password() const
1100 Returns the connection's host name; it may be empty.
1104 QString
QSqlDatabase::hostName() const
1110 Returns the connection's driver name.
1112 \sa addDatabase(), driver()
1114 QString
QSqlDatabase::driverName() const
1120 Returns the connection's port number. The value is undefined if
1121 the port number has not been set.
1125 int QSqlDatabase::port() const
1131 Returns the database driver used to access the database
1134 \sa addDatabase() drivers()
1137 QSqlDriver
* QSqlDatabase::driver() const
1143 Returns information about the last error that occurred on the
1146 Failures that occur in conjunction with an individual query are
1147 reported by QSqlQuery::lastError().
1149 \sa QSqlError, QSqlQuery::lastError()
1152 QSqlError
QSqlDatabase::lastError() const
1154 return d
->driver
->lastError();
1159 Returns a list of the database's tables, system tables and views,
1160 as specified by the parameter \a type.
1162 \sa primaryIndex(), record()
1165 QStringList
QSqlDatabase::tables(QSql::TableType type
) const
1167 return d
->driver
->tables(type
);
1171 Returns the primary index for table \a tablename. If no primary
1172 index exists an empty QSqlIndex is returned.
1174 \sa tables(), record()
1177 QSqlIndex
QSqlDatabase::primaryIndex(const QString
& tablename
) const
1179 return d
->driver
->primaryIndex(tablename
);
1184 Returns a QSqlRecord populated with the names of all the fields in
1185 the table (or view) called \a tablename. The order in which the
1186 fields appear in the record is undefined. If no such table (or
1187 view) exists, an empty record is returned.
1190 QSqlRecord
QSqlDatabase::record(const QString
& tablename
) const
1192 return d
->driver
->record(tablename
);
1197 Sets database-specific \a options. This must be done before the
1198 connection is opened or it has no effect (or you can close() the
1199 connection, call this function and open() the connection again).
1201 The format of the \a options string is a semicolon separated list
1202 of option names or option=value pairs. The options depend on the
1203 database client used:
1206 \header \i ODBC \i MySQL \i PostgreSQL
1211 \i SQL_ATTR_ACCESS_MODE
1212 \i SQL_ATTR_LOGIN_TIMEOUT
1213 \i SQL_ATTR_CONNECTION_TIMEOUT
1214 \i SQL_ATTR_CURRENT_CATALOG
1215 \i SQL_ATTR_METADATA_ID
1216 \i SQL_ATTR_PACKET_SIZE
1217 \i SQL_ATTR_TRACEFILE
1219 \i SQL_ATTR_CONNECTION_POOLING
1220 \i SQL_ATTR_ODBC_VERSION
1226 \i CLIENT_FOUND_ROWS
1227 \i CLIENT_IGNORE_SPACE
1231 \i CLIENT_INTERACTIVE
1233 \i MYSQL_OPT_RECONNECT
1245 \header \i DB2 \i OCI \i TDS
1250 \i SQL_ATTR_ACCESS_MODE
1251 \i SQL_ATTR_LOGIN_TIMEOUT
1256 \i OCI_ATTR_PREFETCH_ROWS
1257 \i OCI_ATTR_PREFETCH_MEMORY
1263 \header \i SQLite \i Interbase
1268 \i QSQLITE_BUSY_TIMEOUT
1269 \i QSQLITE_OPEN_READONLY
1275 \i ISC_DPB_SQL_ROLE_NAME
1281 \snippet doc/src/snippets/code/src_sql_kernel_qsqldatabase.cpp 4
1283 Refer to the client library documentation for more information
1284 about the different options.
1286 \sa connectOptions()
1289 void QSqlDatabase::setConnectOptions(const QString
&options
)
1292 d
->connOptions
= options
;
1296 Returns the connection options string used for this connection.
1297 The string may be empty.
1299 \sa setConnectOptions()
1301 QString
QSqlDatabase::connectOptions() const
1303 return d
->connOptions
;
1307 Returns true if a driver called \a name is available; otherwise
1313 bool QSqlDatabase::isDriverAvailable(const QString
& name
)
1315 return drivers().contains(name
);
1318 /*! \fn QSqlDatabase QSqlDatabase::addDatabase(QSqlDriver* driver, const QString& connectionName)
1320 This overload is useful when you want to create a database
1321 connection with a \l{QSqlDriver} {driver} you instantiated
1322 yourself. It might be your own database driver, or you might just
1323 need to instantiate one of the Qt drivers yourself. If you do
1324 this, it is recommended that you include the driver code in your
1325 application. For example, you can create a PostgreSQL connection
1326 with your own QPSQL driver like this:
1328 \snippet doc/src/snippets/code/src_sql_kernel_qsqldatabase.cpp 5
1330 \snippet doc/src/snippets/code/src_sql_kernel_qsqldatabase.cpp 6
1332 The above code sets up a PostgreSQL connection and instantiates a
1333 QPSQLDriver object. Next, addDatabase() is called to add the
1334 connection to the known connections so that it can be used by the
1335 Qt SQL classes. When a driver is instantiated with a connection
1336 handle (or set of handles), Qt assumes that you have already
1337 opened the database connection.
1339 \note We assume that \c qtdir is the directory where Qt is
1340 installed. This will pull in the code that is needed to use the
1341 PostgreSQL client library and to instantiate a QPSQLDriver object,
1342 assuming that you have the PostgreSQL headers somewhere in your
1343 include search path.
1345 Remember that you must link your application against the database
1346 client library. Make sure the client library is in your linker's
1347 search path, and add lines like these to your \c{.pro} file:
1349 \snippet doc/src/snippets/code/src_sql_kernel_qsqldatabase.cpp 7
1351 The method described works for all the supplied drivers. The only
1352 difference will be in the driver constructor arguments. Here is a
1353 table of the drivers included with Qt, their source code files,
1354 and their constructor arguments:
1357 \header \i Driver \i Class name \i Constructor arguments \i File to include
1361 \i PGconn *connection
1366 \i MYSQL *connection
1367 \i \c qsql_mysql.cpp
1371 \i OCIEnv *environment, OCISvcCtx *serviceContext
1376 \i SQLHANDLE environment, SQLHANDLE connection
1381 \i SQLHANDLE environment, SQLHANDLE connection
1386 \i LOGINREC *loginRecord, DBPROCESS *dbProcess, const QString &hostName
1391 \i sqlite *connection
1392 \i \c qsql_sqlite.cpp
1396 \i isc_db_handle connection
1397 \i \c qsql_ibase.cpp
1400 The host name (or service name) is needed when constructing the
1401 QTDSDriver for creating new connections for internal queries. This
1402 is to prevent blocking when several QSqlQuery objects are used
1405 \warning Adding a database connection with the same connection
1406 name as an existing connection, causes the existing connection to
1407 be replaced by the new one.
1409 \warning The SQL framework takes ownership of the \a driver. It
1410 must not be deleted. To remove the connection, use
1415 QSqlDatabase
QSqlDatabase::addDatabase(QSqlDriver
* driver
, const QString
& connectionName
)
1417 QSqlDatabase
db(driver
);
1418 QSqlDatabasePrivate::addDatabase(db
, connectionName
);
1423 Returns true if the QSqlDatabase has a valid driver.
1426 \snippet doc/src/snippets/code/src_sql_kernel_qsqldatabase.cpp 8
1428 bool QSqlDatabase::isValid() const
1430 return d
->driver
&& d
->driver
!= d
->shared_null()->driver
;
1435 Use query.record() instead.
1437 QSqlRecord
QSqlDatabase::record(const QSqlQuery
& query
) const
1438 { return query
.record(); }
1441 Use query.record() instead.
1443 QSqlRecord
QSqlDatabase::recordInfo(const QSqlQuery
& query
) const
1444 { return query
.record(); }
1447 \fn QSqlRecord QSqlDatabase::recordInfo(const QString& tablename) const
1449 Use record() instead.
1454 Clones the database connection \a other and and stores it as \a
1455 connectionName. All the settings from the original database, e.g.
1456 databaseName(), hostName(), etc., are copied across. Does nothing
1457 if \a other is an invalid database. Returns the newly created
1458 database connection.
1460 \note The new connection has not been opened. Before using the new
1461 connection, you must call open().
1463 QSqlDatabase
QSqlDatabase::cloneDatabase(const QSqlDatabase
&other
, const QString
&connectionName
)
1465 if (!other
.isValid())
1466 return QSqlDatabase();
1468 QSqlDatabase
db(other
.driverName());
1469 db
.d
->copy(other
.d
);
1470 QSqlDatabasePrivate::addDatabase(db
, connectionName
);
1477 Returns the connection name, which may be empty. \note The
1478 connection name is not the \l{databaseName()} {database name}.
1482 QString
QSqlDatabase::connectionName() const
1490 Sets the default numerical precision policy used by queries created
1491 on this database connection to \a precisionPolicy.
1493 Note: Drivers that don't support fetching numerical values with low
1494 precision will ignore the precision policy. You can use
1495 QSqlDriver::hasFeature() to find out whether a driver supports this
1498 Note: Setting the default precision policy to \a precisionPolicy
1499 doesn't affect any currently active queries.
1501 \sa QSql::NumericalPrecisionPolicy, numericalPrecisionPolicy(),
1502 QSqlQuery::setNumericalPrecisionPolicy(), QSqlQuery::numericalPrecisionPolicy()
1504 void QSqlDatabase::setNumericalPrecisionPolicy(QSql::NumericalPrecisionPolicy precisionPolicy
)
1507 driver()->setNumericalPrecisionPolicy(precisionPolicy
);
1508 d
->precisionPolicy
= precisionPolicy
;
1514 Returns the current default precision policy for the database connection.
1516 \sa QSql::NumericalPrecisionPolicy, setNumericalPrecisionPolicy(),
1517 QSqlQuery::numericalPrecisionPolicy(), QSqlQuery::setNumericalPrecisionPolicy()
1519 QSql::NumericalPrecisionPolicy
QSqlDatabase::numericalPrecisionPolicy() const
1522 return driver()->numericalPrecisionPolicy();
1524 return d
->precisionPolicy
;
1528 #ifndef QT_NO_DEBUG_STREAM
1529 QDebug
operator<<(QDebug dbg
, const QSqlDatabase
&d
)
1532 dbg
.nospace() << "QSqlDatabase(invalid)";
1536 dbg
.nospace() << "QSqlDatabase(driver=\"" << d
.driverName() << "\", database=\""
1537 << d
.databaseName() << "\", host=\"" << d
.hostName() << "\", port=" << d
.port()
1538 << ", user=\"" << d
.userName() << "\", open=" << d
.isOpen() << ")";