1 /****************************************************************************
3 ** Copyright (C) 2011 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 ** GNU Lesser General Public License Usage
11 ** This file may be used under the terms of the GNU Lesser General Public
12 ** License version 2.1 as published by the Free Software Foundation and
13 ** appearing in the file LICENSE.LGPL included in the packaging of this
14 ** file. Please review the following information to ensure the GNU Lesser
15 ** General Public License version 2.1 requirements will be met:
16 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
18 ** In addition, as a special exception, Nokia gives you certain additional
19 ** rights. These rights are described in the Nokia Qt LGPL Exception
20 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
22 ** GNU General Public License Usage
23 ** Alternatively, this file may be used under the terms of the GNU General
24 ** Public License version 3.0 as published by the Free Software Foundation
25 ** and appearing in the file LICENSE.GPL included in the packaging of this
26 ** file. Please review the following information to ensure the GNU General
27 ** Public License version 3.0 requirements will be met:
28 ** http://www.gnu.org/copyleft/gpl.html.
31 ** Alternatively, this file may be used in accordance with the terms and
32 ** conditions contained in a signed written agreement between you and Nokia.
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 // conflicting RETCODE typedef between odbc and freetds
64 #define RETCODE DBRETCODE
65 #include "../drivers/tds/qsql_tds.h"
69 #include "../drivers/db2/qsql_db2.h"
72 #include "../drivers/sqlite/qsql_sqlite.h"
75 #include "../drivers/sqlite2/qsql_sqlite2.h"
78 #undef SQL_FLOAT // avoid clash with ODBC
84 #define SCHAR IBASE_SCHAR // avoid clash with ODBC (older versions of ibase.h with Firebird)
85 #include "../drivers/ibase/qsql_ibase.h"
90 #include "qcoreapplication.h"
91 #include "qreadwritelock.h"
92 #include "qsqlresult.h"
93 #include "qsqldriver.h"
94 #include "qsqldriverplugin.h"
95 #include "qsqlindex.h"
96 #include "private/qfactoryloader_p.h"
97 #include "private/qsqlnulldriver_p.h"
104 #ifndef QT_NO_LIBRARY
105 Q_GLOBAL_STATIC_WITH_ARGS(QFactoryLoader, loader,
106 (QSqlDriverFactoryInterface_iid,
107 QLatin1String("/sqldrivers")))
110 QT_STATIC_CONST_IMPL char *QSqlDatabase::defaultConnection = "qt_sql_default_connection";
112 typedef QHash<QString, QSqlDriverCreatorBase*> DriverDict;
114 class QConnectionDict: public QHash<QString, QSqlDatabase>
117 inline bool contains_ts(const QString &key)
119 QReadLocker locker(&lock);
120 return contains(key);
122 inline QStringList keys_ts() const
124 QReadLocker locker(&lock);
128 mutable QReadWriteLock lock;
130 Q_GLOBAL_STATIC(QConnectionDict, dbDict)
132 class QSqlDatabasePrivate
135 QSqlDatabasePrivate(QSqlDatabase *d, QSqlDriver *dr = 0):
142 precisionPolicy = driver->numericalPrecisionPolicy();
144 precisionPolicy= QSql::LowPrecisionDouble;
146 QSqlDatabasePrivate(const QSqlDatabasePrivate &other);
147 ~QSqlDatabasePrivate();
148 void init(const QString& type);
149 void copy(const QSqlDatabasePrivate *other);
163 QSql::NumericalPrecisionPolicy precisionPolicy;
165 static QSqlDatabasePrivate *shared_null();
166 static QSqlDatabase database(const QString& name, bool open);
167 static void addDatabase(const QSqlDatabase &db, const QString & name);
168 static void removeDatabase(const QString& name);
169 static void invalidateDb(const QSqlDatabase &db, const QString &name, bool doWarn = true);
170 static DriverDict &driverDict();
171 static void cleanConnections();
174 QSqlDatabasePrivate::QSqlDatabasePrivate(const QSqlDatabasePrivate &other)
178 dbname = other.dbname;
182 drvName = other.drvName;
184 connOptions = other.connOptions;
185 driver = other.driver;
186 precisionPolicy = other.precisionPolicy;
189 QSqlDatabasePrivate::~QSqlDatabasePrivate()
191 if (driver != shared_null()->driver)
195 void QSqlDatabasePrivate::cleanConnections()
197 QConnectionDict *dict = dbDict();
199 QWriteLocker locker(&dict->lock);
201 QConnectionDict::iterator it = dict->begin();
202 while (it != dict->end()) {
203 invalidateDb(it.value(), it.key(), false);
209 static bool qDriverDictInit = false;
210 static void cleanDriverDict()
212 qDeleteAll(QSqlDatabasePrivate::driverDict());
213 QSqlDatabasePrivate::driverDict().clear();
214 QSqlDatabasePrivate::cleanConnections();
215 qDriverDictInit = false;
218 DriverDict &QSqlDatabasePrivate::driverDict()
220 static DriverDict dict;
221 if (!qDriverDictInit) {
222 qDriverDictInit = true;
223 qAddPostRoutine(cleanDriverDict);
228 QSqlDatabasePrivate *QSqlDatabasePrivate::shared_null()
230 static QSqlNullDriver dr;
231 static QSqlDatabasePrivate n(NULL, &dr);
235 void QSqlDatabasePrivate::invalidateDb(const QSqlDatabase &db, const QString &name, bool doWarn)
237 if (db.d->ref != 1 && doWarn) {
238 qWarning("QSqlDatabasePrivate::removeDatabase: connection '%s' is still in use, "
239 "all queries will cease to work.", name.toLocal8Bit().constData());
241 db.d->connName.clear();
245 void QSqlDatabasePrivate::removeDatabase(const QString &name)
247 QConnectionDict *dict = dbDict();
249 QWriteLocker locker(&dict->lock);
251 if (!dict->contains(name))
254 invalidateDb(dict->take(name), name);
257 void QSqlDatabasePrivate::addDatabase(const QSqlDatabase &db, const QString &name)
259 QConnectionDict *dict = dbDict();
261 QWriteLocker locker(&dict->lock);
263 if (dict->contains(name)) {
264 invalidateDb(dict->take(name), name);
265 qWarning("QSqlDatabasePrivate::addDatabase: duplicate connection name '%s', old "
266 "connection removed.", name.toLocal8Bit().data());
268 dict->insert(name, db);
269 db.d->connName = name;
274 QSqlDatabase QSqlDatabasePrivate::database(const QString& name, bool open)
276 const QConnectionDict *dict = dbDict();
279 dict->lock.lockForRead();
280 QSqlDatabase db = dict->value(name);
282 if (db.isValid() && !db.isOpen() && open) {
284 qWarning() << "QSqlDatabasePrivate::database: unable to open database:" << db.lastError().text();
292 Copies the connection data from \a other.
294 void QSqlDatabasePrivate::copy(const QSqlDatabasePrivate *other)
297 dbname = other->dbname;
298 uname = other->uname;
299 pword = other->pword;
300 hname = other->hname;
301 drvName = other->drvName;
303 connOptions = other->connOptions;
304 precisionPolicy = other->precisionPolicy;
307 void QSqlDatabasePrivate::disable()
309 if (driver != shared_null()->driver) {
311 driver = shared_null()->driver;
316 \class QSqlDriverCreatorBase
317 \brief The QSqlDriverCreatorBase class is the base class for
318 SQL driver factories.
323 Reimplement createObject() to return an instance of the specific
324 QSqlDriver subclass that you want to provide.
326 See QSqlDatabase::registerSqlDriver() for details.
328 \sa QSqlDriverCreator
332 \fn QSqlDriverCreatorBase::~QSqlDriverCreatorBase()
334 Destroys the SQL driver creator object.
338 \fn QSqlDriver *QSqlDriverCreatorBase::createObject() const
340 Reimplement this function to returns a new instance of a
345 \class QSqlDriverCreator
346 \brief The QSqlDriverCreator class is a template class that
347 provides a SQL driver factory for a specific driver type.
352 QSqlDriverCreator<T> instantiates objects of type T, where T is a
355 See QSqlDatabase::registerSqlDriver() for details.
359 \fn QSqlDriver *QSqlDriverCreator::createObject() const
365 \brief The QSqlDatabase class represents a connection to
372 The QSqlDatabase class provides an interface for accessing a
373 database through a connection. An instance of QSqlDatabase
374 represents the connection. The connection provides access to the
375 database via one of the \l{SQL Database Drivers#Supported
376 Databases} {supported database drivers}, which are derived from
377 QSqlDriver. Alternatively, you can subclass your own database
378 driver from QSqlDriver. See \l{How to Write Your Own Database
379 Driver} for more information.
381 Create a connection (i.e., an instance of QSqlDatabase) by calling
382 one of the static addDatabase() functions, where you specify
383 \l{SQL Database Drivers#Supported Databases} {the driver or type
384 of driver} to use (i.e., what kind of database will you access?)
385 and a connection name. A connection is known by its own name,
386 \e{not} by the name of the database it connects to. You can have
387 multiple connections to one database. QSqlDatabase also supports
388 the concept of a \e{default} connection, which is the unnamed
389 connection. To create the default connection, don't pass the
390 connection name argument when you call addDatabase().
391 Subsequently, when you call any static member function that takes
392 the connection name argument, if you don't pass the connection
393 name argument, the default connection is assumed. The following
394 snippet shows how to create and open a default connection to a
397 \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 0
399 Once the QSqlDatabase object has been created, set the connection
400 parameters with setDatabaseName(), setUserName(), setPassword(),
401 setHostName(), setPort(), and setConnectOptions(). Then call
402 open() to activate the physical connection to the database. The
403 connection is not usable until you open it.
405 The connection defined above will be the \e{default} connection,
406 because we didn't give a connection name to \l{QSqlDatabase::}
407 {addDatabase()}. Subsequently, you can get the default connection
408 by calling database() without the connection name argument:
410 \snippet doc/src/snippets/sqldatabase/sqldatabase.cpp 1
412 QSqlDatabase is a value class. Changes made to a database
413 connection via one instance of QSqlDatabase will affect other
414 instances of QSqlDatabase that represent the same connection. Use
415 cloneDatabase() to create an independent database connection based
418 If you create multiple database connections, specify a unique
419 connection name for each one, when you call addDatabase(). Use
420 database() with a connection name to get that connection. Use
421 removeDatabase() with a connection name to remove a connection.
422 QSqlDatabase outputs a warning if you try to remove a connection
423 referenced by other QSqlDatabase objects. Use contains() to see if
424 a given connection name is in the list of connections.
426 Once a connection is established, you can call tables() to get the
427 list of tables in the database, call primaryIndex() to get a
428 table's primary index, and call record() to get meta-information
429 about a table's fields (e.g., field names).
431 \note QSqlDatabase::exec() is deprecated. Use QSqlQuery::exec()
434 If the driver supports transactions, use transaction() to start a
435 transaction, and commit() or rollback() to complete it. Use
436 \l{QSqlDriver::} {hasFeature()} to ask if the driver supports
437 transactions. \note When using transactions, you must start the
438 transaction before you create your query.
440 If an error occurrs, lastError() will return information about it.
442 Get the names of the available SQL drivers with drivers(). Check
443 for the presence of a particular driver with isDriverAvailable().
444 If you have created your own custom driver, you must register it
445 with registerSqlDriver().
447 \sa QSqlDriver, QSqlQuery, {QtSql Module}, {Threads and the SQL Module}
450 /*! \fn QSqlDatabase QSqlDatabase::addDatabase(const QString &type, const QString &connectionName)
453 Adds a database to the list of database connections using the
454 driver \a type and the connection name \a connectionName. If
455 there already exists a database connection called \a
456 connectionName, that connection is removed.
458 The database connection is referred to by \a connectionName. The
459 newly added database connection is returned.
461 If \a type is not available or could not be loaded, isValid() returns false.
463 If \a connectionName is not specified, the new connection becomes
464 the default connection for the application, and subsequent calls
465 to database() without the connection name argument will return the
466 default connection. If a \a connectionName is provided here, use
467 database(\a connectionName) to retrieve the connection.
469 \warning If you add a connection with the same name as an existing
470 connection, the new connection replaces the old one. If you call
471 this function more than once without specifying \a connectionName,
472 the default connection will be the one replaced.
474 Before using the connection, it must be initialized. e.g., call
475 some or all of setDatabaseName(), setUserName(), setPassword(),
476 setHostName(), setPort(), and setConnectOptions(), and, finally,
479 \sa database() removeDatabase() {Threads and the SQL Module}
481 QSqlDatabase QSqlDatabase::addDatabase(const QString &type, const QString &connectionName)
483 QSqlDatabase db(type);
484 QSqlDatabasePrivate::addDatabase(db, connectionName);
491 Returns the database connection called \a connectionName. The
492 database connection must have been previously added with
493 addDatabase(). If \a open is true (the default) and the database
494 connection is not already open it is opened now. If no \a
495 connectionName is specified the default connection is used. If \a
496 connectionName does not exist in the list of databases, an invalid
497 connection is returned.
499 \sa isOpen() {Threads and the SQL Module}
502 QSqlDatabase QSqlDatabase::database(const QString& connectionName, bool open)
504 return QSqlDatabasePrivate::database(connectionName, open);
510 Removes the database connection \a connectionName from the list of
511 database connections.
513 \warning There should be no open queries on the database
514 connection when this function is called, otherwise a resource leak
519 \snippet doc/src/snippets/code/src_sql_kernel_qsqldatabase.cpp 0
521 The correct way to do it:
523 \snippet doc/src/snippets/code/src_sql_kernel_qsqldatabase.cpp 1
525 To remove the default connection, which may have been created with a
526 call to addDatabase() not specifying a connection name, you can
527 retrieve the default connection name by calling connectionName() on
528 the database returned by database(). Note that if a default database
529 hasn't been created an invalid database will be returned.
531 \sa database() connectionName() {Threads and the SQL Module}
534 void QSqlDatabase::removeDatabase(const QString& connectionName)
536 QSqlDatabasePrivate::removeDatabase(connectionName);
540 Returns a list of all the available database drivers.
542 \sa registerSqlDriver()
545 QStringList QSqlDatabase::drivers()
550 list << QLatin1String("QPSQL7");
551 list << QLatin1String("QPSQL");
554 list << QLatin1String("QMYSQL3");
555 list << QLatin1String("QMYSQL");
558 list << QLatin1String("QODBC3");
559 list << QLatin1String("QODBC");
562 list << QLatin1String("QOCI8");
563 list << QLatin1String("QOCI");
566 list << QLatin1String("QTDS7");
567 list << QLatin1String("QTDS");
570 list << QLatin1String("QDB2");
573 list << QLatin1String("QSQLITE");
575 #ifdef QT_SQL_SQLITE2
576 list << QLatin1String("QSQLITE2");
579 list << QLatin1String("QIBASE");
582 #ifndef QT_NO_LIBRARY
583 if (QFactoryLoader *fl = loader()) {
584 QStringList keys = fl->keys();
585 for (QStringList::const_iterator i = keys.constBegin(); i != keys.constEnd(); ++i) {
586 if (!list.contains(*i))
592 DriverDict dict = QSqlDatabasePrivate::driverDict();
593 for (DriverDict::const_iterator i = dict.constBegin(); i != dict.constEnd(); ++i) {
594 if (!list.contains(i.key()))
602 This function registers a new SQL driver called \a name, within
603 the SQL framework. This is useful if you have a custom SQL driver
604 and don't want to compile it as a plugin.
607 \snippet doc/src/snippets/code/src_sql_kernel_qsqldatabase.cpp 2
609 QSqlDatabase takes ownership of the \a creator pointer, so you
610 mustn't delete it yourself.
614 void QSqlDatabase::registerSqlDriver(const QString& name, QSqlDriverCreatorBase *creator)
616 delete QSqlDatabasePrivate::driverDict().take(name);
618 QSqlDatabasePrivate::driverDict().insert(name, creator);
624 Returns true if the list of database connections contains \a
625 connectionName; otherwise returns false.
627 \sa connectionNames(), database(), {Threads and the SQL Module}
630 bool QSqlDatabase::contains(const QString& connectionName)
632 return dbDict()->contains_ts(connectionName);
638 Returns a list containing the names of all connections.
640 \sa contains(), database(), {Threads and the SQL Module}
642 QStringList QSqlDatabase::connectionNames()
644 return dbDict()->keys_ts();
650 Creates a QSqlDatabase connection that uses the driver referred
651 to by \a type. If the \a type is not recognized, the database
652 connection will have no functionality.
654 The currently available driver types are:
657 \header \i Driver Type \i Description
658 \row \i QDB2 \i IBM DB2
659 \row \i QIBASE \i Borland InterBase Driver
660 \row \i QMYSQL \i MySQL Driver
661 \row \i QOCI \i Oracle Call Interface Driver
662 \row \i QODBC \i ODBC Driver (includes Microsoft SQL Server)
663 \row \i QPSQL \i PostgreSQL Driver
664 \row \i QSQLITE \i SQLite version 3 or above
665 \row \i QSQLITE2 \i SQLite version 2
666 \row \i QTDS \i Sybase Adaptive Server
669 Additional third party drivers, including your own custom
670 drivers, can be loaded dynamically.
672 \sa {SQL Database Drivers}, registerSqlDriver(), drivers()
675 QSqlDatabase::QSqlDatabase(const QString &type)
677 d = new QSqlDatabasePrivate(this);
684 Creates a database connection using the given \a driver.
687 QSqlDatabase::QSqlDatabase(QSqlDriver *driver)
689 d = new QSqlDatabasePrivate(this, driver);
693 Creates an empty, invalid QSqlDatabase object. Use addDatabase(),
694 removeDatabase(), and database() to get valid QSqlDatabase
697 QSqlDatabase::QSqlDatabase()
699 d = QSqlDatabasePrivate::shared_null();
704 Creates a copy of \a other.
706 QSqlDatabase::QSqlDatabase(const QSqlDatabase &other)
713 Assigns \a other to this object.
715 QSqlDatabase &QSqlDatabase::operator=(const QSqlDatabase &other)
717 qAtomicAssign(d, other.d);
724 Create the actual driver instance \a type.
727 void QSqlDatabasePrivate::init(const QString &type)
733 if (type == QLatin1String("QPSQL") || type == QLatin1String("QPSQL7"))
734 driver = new QPSQLDriver();
737 if (type == QLatin1String("QMYSQL") || type == QLatin1String("QMYSQL3"))
738 driver = new QMYSQLDriver();
741 if (type == QLatin1String("QODBC") || type == QLatin1String("QODBC3"))
742 driver = new QODBCDriver();
745 if (type == QLatin1String("QOCI") || type == QLatin1String("QOCI8"))
746 driver = new QOCIDriver();
749 if (type == QLatin1String("QTDS") || type == QLatin1String("QTDS7"))
750 driver = new QTDSDriver();
753 if (type == QLatin1String("QDB2"))
754 driver = new QDB2Driver();
757 if (type == QLatin1String("QSQLITE"))
758 driver = new QSQLiteDriver();
760 #ifdef QT_SQL_SQLITE2
761 if (type == QLatin1String("QSQLITE2"))
762 driver = new QSQLite2Driver();
765 if (type == QLatin1String("QIBASE"))
766 driver = new QIBaseDriver();
771 DriverDict dict = QSqlDatabasePrivate::driverDict();
772 for (DriverDict::const_iterator it = dict.constBegin();
773 it != dict.constEnd() && !driver; ++it) {
774 if (type == it.key()) {
775 driver = ((QSqlDriverCreatorBase*)(*it))->createObject();
780 #ifndef QT_NO_LIBRARY
781 if (!driver && loader()) {
782 if (QSqlDriverFactoryInterface *factory = qobject_cast<QSqlDriverFactoryInterface*>(loader()->instance(type)))
783 driver = factory->create(type);
785 #endif // QT_NO_LIBRARY
788 qWarning("QSqlDatabase: %s driver not loaded", type.toLatin1().data());
789 qWarning("QSqlDatabase: available drivers: %s",
790 QSqlDatabase::drivers().join(QLatin1String(" ")).toLatin1().data());
791 if (QCoreApplication::instance() == 0)
792 qWarning("QSqlDatabase: an instance of QCoreApplication is required for loading driver plugins");
793 driver = shared_null()->driver;
798 Destroys the object and frees any allocated resources.
800 If this is the last QSqlDatabase object that uses a certain
801 database connection, the database connection is automatically closed.
806 QSqlDatabase::~QSqlDatabase()
808 if (!d->ref.deref()) {
815 Executes a SQL statement on the database and returns a QSqlQuery
816 object. Use lastError() to retrieve error information. If \a
817 query is empty, an empty, invalid query is returned and
818 lastError() is not affected.
820 \sa QSqlQuery, lastError()
823 QSqlQuery QSqlDatabase::exec(const QString & query) const
825 QSqlQuery r(d->driver->createResult());
826 if (!query.isEmpty()) {
828 d->driver->setLastError(r.lastError());
834 Opens the database connection using the current connection
835 values. Returns true on success; otherwise returns false. Error
836 information can be retrieved using lastError().
838 \sa lastError() setDatabaseName() setUserName() setPassword()
839 \sa setHostName() setPort() setConnectOptions()
842 bool QSqlDatabase::open()
844 return d->driver->open(d->dbname, d->uname, d->pword, d->hname,
845 d->port, d->connOptions);
851 Opens the database connection using the given \a user name and \a
852 password. Returns true on success; otherwise returns false. Error
853 information can be retrieved using the lastError() function.
855 This function does not store the password it is given. Instead,
856 the password is passed directly to the driver for opening the
857 connection and it is then discarded.
862 bool QSqlDatabase::open(const QString& user, const QString& password)
865 return d->driver->open(d->dbname, user, password, d->hname,
866 d->port, d->connOptions);
870 Closes the database connection, freeing any resources acquired, and
871 invalidating any existing QSqlQuery objects that are used with the
874 This will also affect copies of this QSqlDatabase object.
879 void QSqlDatabase::close()
885 Returns true if the database connection is currently open;
886 otherwise returns false.
889 bool QSqlDatabase::isOpen() const
891 return d->driver->isOpen();
895 Returns true if there was an error opening the database
896 connection; otherwise returns false. Error information can be
897 retrieved using the lastError() function.
900 bool QSqlDatabase::isOpenError() const
902 return d->driver->isOpenError();
906 Begins a transaction on the database if the driver supports
907 transactions. Returns \c{true} if the operation succeeded.
908 Otherwise it returns \c{false}.
910 \sa QSqlDriver::hasFeature(), commit(), rollback()
912 bool QSqlDatabase::transaction()
914 if (!d->driver->hasFeature(QSqlDriver::Transactions))
916 return d->driver->beginTransaction();
920 Commits a transaction to the database if the driver supports
921 transactions and a transaction() has been started. Returns \c{true}
922 if the operation succeeded. Otherwise it returns \c{false}.
924 \note For some databases, the commit will fail and return \c{false}
925 if there is an \l{QSqlQuery::isActive()} {active query} using the
926 database for a \c{SELECT}. Make the query \l{QSqlQuery::isActive()}
927 {inactive} before doing the commit.
929 Call lastError() to get information about errors.
931 \sa QSqlQuery::isActive() QSqlDriver::hasFeature() rollback()
933 bool QSqlDatabase::commit()
935 if (!d->driver->hasFeature(QSqlDriver::Transactions))
937 return d->driver->commitTransaction();
941 Rolls back a transaction on the database, if the driver supports
942 transactions and a transaction() has been started. Returns \c{true}
943 if the operation succeeded. Otherwise it returns \c{false}.
945 \note For some databases, the rollback will fail and return
946 \c{false} if there is an \l{QSqlQuery::isActive()} {active query}
947 using the database for a \c{SELECT}. Make the query
948 \l{QSqlQuery::isActive()} {inactive} before doing the rollback.
950 Call lastError() to get information about errors.
952 \sa QSqlQuery::isActive() QSqlDriver::hasFeature() commit()
954 bool QSqlDatabase::rollback()
956 if (!d->driver->hasFeature(QSqlDriver::Transactions))
958 return d->driver->rollbackTransaction();
962 Sets the connection's database name to \a name. To have effect,
963 the database name must be set \e{before} the connection is
964 \l{open()} {opened}. Alternatively, you can close() the
965 connection, set the database name, and call open() again. \note
966 The \e{database name} is not the \e{connection name}. The
967 connection name must be passed to addDatabase() at connection
970 For the QOCI (Oracle) driver, the database name is the TNS
973 For the QODBC driver, the \a name can either be a DSN, a DSN
974 filename (in which case the file must have a \c .dsn extension),
975 or a connection string.
977 For example, Microsoft Access users can use the following
978 connection string to open an \c .mdb file directly, instead of
979 having to create a DSN entry in the ODBC manager:
981 \snippet doc/src/snippets/code/src_sql_kernel_qsqldatabase.cpp 3
983 There is no default value.
985 \sa databaseName() setUserName() setPassword() setHostName()
986 \sa setPort() setConnectOptions() open()
989 void QSqlDatabase::setDatabaseName(const QString& name)
996 Sets the connection's user name to \a name. To have effect, the
997 user name must be set \e{before} the connection is \l{open()}
998 {opened}. Alternatively, you can close() the connection, set the
999 user name, and call open() again.
1001 There is no default value.
1003 \sa userName() setDatabaseName() setPassword() setHostName()
1004 \sa setPort() setConnectOptions() open()
1007 void QSqlDatabase::setUserName(const QString& name)
1014 Sets the connection's password to \a password. To have effect, the
1015 password must be set \e{before} the connection is \l{open()}
1016 {opened}. Alternatively, you can close() the connection, set the
1017 password, and call open() again.
1019 There is no default value.
1021 \warning This function stores the password in plain text within
1022 Qt. Use the open() call that takes a password as parameter to
1023 avoid this behavior.
1025 \sa password() setUserName() setDatabaseName() setHostName()
1026 \sa setPort() setConnectOptions() open()
1029 void QSqlDatabase::setPassword(const QString& password)
1032 d->pword = password;
1036 Sets the connection's host name to \a host. To have effect, the
1037 host name must be set \e{before} the connection is \l{open()}
1038 {opened}. Alternatively, you can close() the connection, set the
1039 host name, and call open() again.
1041 There is no default value.
1043 \sa hostName() setUserName() setPassword() setDatabaseName()
1044 \sa setPort() setConnectOptions() open()
1047 void QSqlDatabase::setHostName(const QString& host)
1054 Sets the connection's port number to \a port. To have effect, the
1055 port number must be set \e{before} the connection is \l{open()}
1056 {opened}. Alternatively, you can close() the connection, set the
1057 port number, and call open() again..
1059 There is no default value.
1061 \sa port() setUserName() setPassword() setHostName()
1062 \sa setDatabaseName() setConnectOptions() open()
1065 void QSqlDatabase::setPort(int port)
1072 Returns the connection's database name, which may be empty.
1073 \note The database name is not the connection name.
1075 \sa setDatabaseName()
1077 QString QSqlDatabase::databaseName() const
1083 Returns the connection's user name; it may be empty.
1087 QString QSqlDatabase::userName() const
1093 Returns the connection's password. If the password was not set
1094 with setPassword(), and if the password was given in the open()
1095 call, or if no password was used, an empty string is returned.
1097 QString QSqlDatabase::password() const
1103 Returns the connection's host name; it may be empty.
1107 QString QSqlDatabase::hostName() const
1113 Returns the connection's driver name.
1115 \sa addDatabase(), driver()
1117 QString QSqlDatabase::driverName() const
1123 Returns the connection's port number. The value is undefined if
1124 the port number has not been set.
1128 int QSqlDatabase::port() const
1134 Returns the database driver used to access the database
1137 \sa addDatabase() drivers()
1140 QSqlDriver* QSqlDatabase::driver() const
1146 Returns information about the last error that occurred on the
1149 Failures that occur in conjunction with an individual query are
1150 reported by QSqlQuery::lastError().
1152 \sa QSqlError, QSqlQuery::lastError()
1155 QSqlError QSqlDatabase::lastError() const
1157 return d->driver->lastError();
1162 Returns a list of the database's tables, system tables and views,
1163 as specified by the parameter \a type.
1165 \sa primaryIndex(), record()
1168 QStringList QSqlDatabase::tables(QSql::TableType type) const
1170 return d->driver->tables(type);
1174 Returns the primary index for table \a tablename. If no primary
1175 index exists an empty QSqlIndex is returned.
1177 \sa tables(), record()
1180 QSqlIndex QSqlDatabase::primaryIndex(const QString& tablename) const
1182 return d->driver->primaryIndex(tablename);
1187 Returns a QSqlRecord populated with the names of all the fields in
1188 the table (or view) called \a tablename. The order in which the
1189 fields appear in the record is undefined. If no such table (or
1190 view) exists, an empty record is returned.
1193 QSqlRecord QSqlDatabase::record(const QString& tablename) const
1195 return d->driver->record(tablename);
1200 Sets database-specific \a options. This must be done before the
1201 connection is opened or it has no effect (or you can close() the
1202 connection, call this function and open() the connection again).
1204 The format of the \a options string is a semicolon separated list
1205 of option names or option=value pairs. The options depend on the
1206 database client used:
1209 \header \i ODBC \i MySQL \i PostgreSQL
1214 \i SQL_ATTR_ACCESS_MODE
1215 \i SQL_ATTR_LOGIN_TIMEOUT
1216 \i SQL_ATTR_CONNECTION_TIMEOUT
1217 \i SQL_ATTR_CURRENT_CATALOG
1218 \i SQL_ATTR_METADATA_ID
1219 \i SQL_ATTR_PACKET_SIZE
1220 \i SQL_ATTR_TRACEFILE
1222 \i SQL_ATTR_CONNECTION_POOLING
1223 \i SQL_ATTR_ODBC_VERSION
1229 \i CLIENT_FOUND_ROWS
1230 \i CLIENT_IGNORE_SPACE
1234 \i CLIENT_INTERACTIVE
1236 \i MYSQL_OPT_RECONNECT
1248 \header \i DB2 \i OCI \i TDS
1253 \i SQL_ATTR_ACCESS_MODE
1254 \i SQL_ATTR_LOGIN_TIMEOUT
1259 \i OCI_ATTR_PREFETCH_ROWS
1260 \i OCI_ATTR_PREFETCH_MEMORY
1266 \header \i SQLite \i Interbase
1271 \i QSQLITE_BUSY_TIMEOUT
1272 \i QSQLITE_OPEN_READONLY
1273 \i QSQLITE_ENABLE_SHARED_CACHE
1279 \i ISC_DPB_SQL_ROLE_NAME
1285 \snippet doc/src/snippets/code/src_sql_kernel_qsqldatabase.cpp 4
1287 Refer to the client library documentation for more information
1288 about the different options.
1290 \sa connectOptions()
1293 void QSqlDatabase::setConnectOptions(const QString &options)
1296 d->connOptions = options;
1300 Returns the connection options string used for this connection.
1301 The string may be empty.
1303 \sa setConnectOptions()
1305 QString QSqlDatabase::connectOptions() const
1307 return d->connOptions;
1311 Returns true if a driver called \a name is available; otherwise
1317 bool QSqlDatabase::isDriverAvailable(const QString& name)
1319 return drivers().contains(name);
1322 /*! \fn QSqlDatabase QSqlDatabase::addDatabase(QSqlDriver* driver, const QString& connectionName)
1324 This overload is useful when you want to create a database
1325 connection with a \l{QSqlDriver} {driver} you instantiated
1326 yourself. It might be your own database driver, or you might just
1327 need to instantiate one of the Qt drivers yourself. If you do
1328 this, it is recommended that you include the driver code in your
1329 application. For example, you can create a PostgreSQL connection
1330 with your own QPSQL driver like this:
1332 \snippet doc/src/snippets/code/src_sql_kernel_qsqldatabase.cpp 5
1334 \snippet doc/src/snippets/code/src_sql_kernel_qsqldatabase.cpp 6
1336 The above code sets up a PostgreSQL connection and instantiates a
1337 QPSQLDriver object. Next, addDatabase() is called to add the
1338 connection to the known connections so that it can be used by the
1339 Qt SQL classes. When a driver is instantiated with a connection
1340 handle (or set of handles), Qt assumes that you have already
1341 opened the database connection.
1343 \note We assume that \c qtdir is the directory where Qt is
1344 installed. This will pull in the code that is needed to use the
1345 PostgreSQL client library and to instantiate a QPSQLDriver object,
1346 assuming that you have the PostgreSQL headers somewhere in your
1347 include search path.
1349 Remember that you must link your application against the database
1350 client library. Make sure the client library is in your linker's
1351 search path, and add lines like these to your \c{.pro} file:
1353 \snippet doc/src/snippets/code/src_sql_kernel_qsqldatabase.cpp 7
1355 The method described works for all the supplied drivers. The only
1356 difference will be in the driver constructor arguments. Here is a
1357 table of the drivers included with Qt, their source code files,
1358 and their constructor arguments:
1361 \header \i Driver \i Class name \i Constructor arguments \i File to include
1365 \i PGconn *connection
1370 \i MYSQL *connection
1371 \i \c qsql_mysql.cpp
1375 \i OCIEnv *environment, OCISvcCtx *serviceContext
1380 \i SQLHANDLE environment, SQLHANDLE connection
1385 \i SQLHANDLE environment, SQLHANDLE connection
1390 \i LOGINREC *loginRecord, DBPROCESS *dbProcess, const QString &hostName
1395 \i sqlite *connection
1396 \i \c qsql_sqlite.cpp
1400 \i isc_db_handle connection
1401 \i \c qsql_ibase.cpp
1404 The host name (or service name) is needed when constructing the
1405 QTDSDriver for creating new connections for internal queries. This
1406 is to prevent blocking when several QSqlQuery objects are used
1409 \warning Adding a database connection with the same connection
1410 name as an existing connection, causes the existing connection to
1411 be replaced by the new one.
1413 \warning The SQL framework takes ownership of the \a driver. It
1414 must not be deleted. To remove the connection, use
1419 QSqlDatabase QSqlDatabase::addDatabase(QSqlDriver* driver, const QString& connectionName)
1421 QSqlDatabase db(driver);
1422 QSqlDatabasePrivate::addDatabase(db, connectionName);
1427 Returns true if the QSqlDatabase has a valid driver.
1430 \snippet doc/src/snippets/code/src_sql_kernel_qsqldatabase.cpp 8
1432 bool QSqlDatabase::isValid() const
1434 return d->driver && d->driver != d->shared_null()->driver;
1438 Clones the database connection \a other and and stores it as \a
1439 connectionName. All the settings from the original database, e.g.
1440 databaseName(), hostName(), etc., are copied across. Does nothing
1441 if \a other is an invalid database. Returns the newly created
1442 database connection.
1444 \note The new connection has not been opened. Before using the new
1445 connection, you must call open().
1447 QSqlDatabase QSqlDatabase::cloneDatabase(const QSqlDatabase &other, const QString &connectionName)
1449 if (!other.isValid())
1450 return QSqlDatabase();
1452 QSqlDatabase db(other.driverName());
1453 db.d->copy(other.d);
1454 QSqlDatabasePrivate::addDatabase(db, connectionName);
1461 Returns the connection name, which may be empty. \note The
1462 connection name is not the \l{databaseName()} {database name}.
1466 QString QSqlDatabase::connectionName() const
1474 Sets the default numerical precision policy used by queries created
1475 on this database connection to \a precisionPolicy.
1477 Note: Drivers that don't support fetching numerical values with low
1478 precision will ignore the precision policy. You can use
1479 QSqlDriver::hasFeature() to find out whether a driver supports this
1482 Note: Setting the default precision policy to \a precisionPolicy
1483 doesn't affect any currently active queries.
1485 \sa QSql::NumericalPrecisionPolicy, numericalPrecisionPolicy(),
1486 QSqlQuery::setNumericalPrecisionPolicy(), QSqlQuery::numericalPrecisionPolicy()
1488 void QSqlDatabase::setNumericalPrecisionPolicy(QSql::NumericalPrecisionPolicy precisionPolicy)
1491 driver()->setNumericalPrecisionPolicy(precisionPolicy);
1492 d->precisionPolicy = precisionPolicy;
1498 Returns the current default precision policy for the database connection.
1500 \sa QSql::NumericalPrecisionPolicy, setNumericalPrecisionPolicy(),
1501 QSqlQuery::numericalPrecisionPolicy(), QSqlQuery::setNumericalPrecisionPolicy()
1503 QSql::NumericalPrecisionPolicy QSqlDatabase::numericalPrecisionPolicy() const
1506 return driver()->numericalPrecisionPolicy();
1508 return d->precisionPolicy;
1512 #ifndef QT_NO_DEBUG_STREAM
1513 QDebug operator<<(QDebug dbg, const QSqlDatabase &d)
1516 dbg.nospace() << "QSqlDatabase(invalid)";
1520 dbg.nospace() << "QSqlDatabase(driver=\"" << d.driverName() << "\", database=\""
1521 << d.databaseName() << "\", host=\"" << d.hostName() << "\", port=" << d.port()
1522 << ", user=\"" << d.userName() << "\", open=" << d.isOpen() << ")";