Updated change log for 4.5.3
[qt-netbsd.git] / src / sql / kernel / qsqldatabase.cpp
blob8284d07c2ee1c9fc9b3a965e91ccb8732bb61cac
1 /****************************************************************************
2 **
3 ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
4 ** All rights reserved.
5 ** Contact: Nokia Corporation (qt-info@nokia.com)
6 **
7 ** This file is part of the QtSql module of the Qt Toolkit.
8 **
9 ** $QT_BEGIN_LICENSE:LGPL$
10 ** Commercial Usage
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.
38 ** $QT_END_LICENSE$
40 ****************************************************************************/
42 #include "qsqldatabase.h"
43 #include "qsqlquery.h"
45 #ifdef Q_OS_WIN32
46 // Conflicting declarations of LPCBYTE in sqlfront.h and winscard.h
47 #define _WINSCARD_H_
48 #endif
50 #ifdef QT_SQL_PSQL
51 #include "../drivers/psql/qsql_psql.h"
52 #endif
53 #ifdef QT_SQL_MYSQL
54 #include "../drivers/mysql/qsql_mysql.h"
55 #endif
56 #ifdef QT_SQL_ODBC
57 #include "../drivers/odbc/qsql_odbc.h"
58 #endif
59 #ifdef QT_SQL_OCI
60 #include "../drivers/oci/qsql_oci.h"
61 #endif
62 #ifdef QT_SQL_TDS
63 #include "../drivers/tds/qsql_tds.h"
64 #endif
65 #ifdef QT_SQL_DB2
66 #include "../drivers/db2/qsql_db2.h"
67 #endif
68 #ifdef QT_SQL_SQLITE
69 #include "../drivers/sqlite/qsql_sqlite.h"
70 #endif
71 #ifdef QT_SQL_SQLITE2
72 #include "../drivers/sqlite2/qsql_sqlite2.h"
73 #endif
74 #ifdef QT_SQL_IBASE
75 #undef SQL_FLOAT // avoid clash with ODBC
76 #undef SQL_DOUBLE
77 #undef SQL_TIMESTAMP
78 #undef SQL_TYPE_TIME
79 #undef SQL_TYPE_DATE
80 #undef SQL_DATE
81 #define SCHAR IBASE_SCHAR // avoid clash with ODBC (older versions of ibase.h with Firebird)
82 #include "../drivers/ibase/qsql_ibase.h"
83 #undef SCHAR
84 #endif
86 #include "qdebug.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"
95 #include "qmutex.h"
96 #include "qhash.h"
97 #include <stdlib.h>
99 QT_BEGIN_NAMESPACE
101 #if !defined(QT_NO_LIBRARY) && !defined(QT_NO_SETTINGS)
102 Q_GLOBAL_STATIC_WITH_ARGS(QFactoryLoader, loader,
103 (QSqlDriverFactoryInterface_iid,
104 QLatin1String("/sqldrivers")))
105 #endif
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>
113 public:
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);
122 return keys();
125 mutable QReadWriteLock lock;
127 Q_GLOBAL_STATIC(QConnectionDict, dbDict)
129 class QSqlDatabasePrivate
131 public:
132 QSqlDatabasePrivate(QSqlDriver *dr = 0):
133 driver(dr),
134 port(-1)
136 ref = 1;
138 QSqlDatabasePrivate(const QSqlDatabasePrivate &other);
139 ~QSqlDatabasePrivate();
140 void init(const QString& type);
141 void copy(const QSqlDatabasePrivate *other);
142 void disable();
144 QAtomicInt ref;
145 QSqlDriver* driver;
146 QString dbname;
147 QString uname;
148 QString pword;
149 QString hname;
150 QString drvName;
151 int port;
152 QString connOptions;
153 QString connName;
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)
166 ref = 1;
167 dbname = other.dbname;
168 uname = other.uname;
169 pword = other.pword;
170 hname = other.hname;
171 drvName = other.drvName;
172 port = other.port;
173 connOptions = other.connOptions;
174 driver = other.driver;
177 QSqlDatabasePrivate::~QSqlDatabasePrivate()
179 if (driver != shared_null()->driver)
180 delete driver;
183 void QSqlDatabasePrivate::cleanConnections()
185 QConnectionDict *dict = dbDict();
186 Q_ASSERT(dict);
187 QWriteLocker locker(&dict->lock);
189 QConnectionDict::iterator it = dict->begin();
190 while (it != dict->end()) {
191 invalidateDb(it.value(), it.key());
192 ++it;
194 dict->clear();
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);
213 return dict;
216 QSqlDatabasePrivate *QSqlDatabasePrivate::shared_null()
218 static QSqlNullDriver dr;
219 static QSqlDatabasePrivate n(&dr);
220 return &n;
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());
228 db.d->disable();
229 db.d->connName.clear();
233 void QSqlDatabasePrivate::removeDatabase(const QString &name)
235 QConnectionDict *dict = dbDict();
236 Q_ASSERT(dict);
237 QWriteLocker locker(&dict->lock);
239 if (!dict->contains(name))
240 return;
242 invalidateDb(dict->take(name), name);
245 void QSqlDatabasePrivate::addDatabase(const QSqlDatabase &db, const QString &name)
247 QConnectionDict *dict = dbDict();
248 Q_ASSERT(dict);
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;
260 /*! \internal
262 QSqlDatabase QSqlDatabasePrivate::database(const QString& name, bool open)
264 const QConnectionDict *dict = dbDict();
265 Q_ASSERT(dict);
267 dict->lock.lockForRead();
268 QSqlDatabase db = dict->value(name);
269 dict->lock.unlock();
270 if (db.isValid() && !db.isOpen() && open) {
271 if (!db.open())
272 qWarning() << "QSqlDatabasePrivate::database: unable to open database:" << db.lastError().text();
275 return db;
279 /*! \internal
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;
289 port = other->port;
290 connOptions = other->connOptions;
293 void QSqlDatabasePrivate::disable()
295 if (driver != shared_null()->driver) {
296 delete driver;
297 driver = shared_null()->driver;
302 \class QSqlDriverCreatorBase
303 \brief The QSqlDriverCreatorBase class is the base class for
304 SQL driver factories.
306 \ingroup database
307 \inmodule QtSql
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
327 QSqlDriver subclass.
331 \class QSqlDriverCreator
332 \brief The QSqlDriverCreator class is a template class that
333 provides a SQL driver factory for a specific driver type.
335 \ingroup database
336 \inmodule QtSql
338 QSqlDriverCreator<T> instantiates objects of type T, where T is a
339 QSqlDriver subclass.
341 See QSqlDatabase::registerSqlDriver() for details.
345 \fn QSqlDriver *QSqlDriverCreator::createObject() const
346 \reimp
350 \class QSqlDatabase
351 \brief The QSqlDatabase class represents a connection to
352 a database.
354 \ingroup database
355 \mainclass
356 \inmodule QtSql
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
381 PostgreSQL database:
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
402 on an existing one.
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()
418 instead.
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)
437 \threadsafe
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,
461 open().
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);
469 return db;
473 \threadsafe
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);
492 \threadsafe
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
499 will occur.
501 Example:
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()
531 QStringList list;
533 #ifdef QT_SQL_PSQL
534 list << QLatin1String("QPSQL7");
535 list << QLatin1String("QPSQL");
536 #endif
537 #ifdef QT_SQL_MYSQL
538 list << QLatin1String("QMYSQL3");
539 list << QLatin1String("QMYSQL");
540 #endif
541 #ifdef QT_SQL_ODBC
542 list << QLatin1String("QODBC3");
543 list << QLatin1String("QODBC");
544 #endif
545 #ifdef QT_SQL_OCI
546 list << QLatin1String("QOCI8");
547 list << QLatin1String("QOCI");
548 #endif
549 #ifdef QT_SQL_TDS
550 list << QLatin1String("QTDS7");
551 list << QLatin1String("QTDS");
552 #endif
553 #ifdef QT_SQL_DB2
554 list << QLatin1String("QDB2");
555 #endif
556 #ifdef QT_SQL_SQLITE
557 list << QLatin1String("QSQLITE");
558 #endif
559 #ifdef QT_SQL_SQLITE2
560 list << QLatin1String("QSQLITE2");
561 #endif
562 #ifdef QT_SQL_IBASE
563 list << QLatin1String("QIBASE");
564 #endif
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))
571 list << *i;
574 #endif
576 DriverDict dict = QSqlDatabasePrivate::driverDict();
577 for (DriverDict::const_iterator i = dict.constBegin(); i != dict.constEnd(); ++i) {
578 if (!list.contains(i.key()))
579 list << i.key();
582 return list;
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.
590 Example:
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.
596 \sa drivers()
598 void QSqlDatabase::registerSqlDriver(const QString& name, QSqlDriverCreatorBase *creator)
600 delete QSqlDatabasePrivate::driverDict().take(name);
601 if (creator)
602 QSqlDatabasePrivate::driverDict().insert(name, creator);
606 \threadsafe
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);
620 \threadsafe
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();
632 \overload
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:
640 \table
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
651 \endtable
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();
662 d->init(type);
666 \overload
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
679 objects.
681 QSqlDatabase::QSqlDatabase()
683 d = QSqlDatabasePrivate::shared_null();
684 d->ref.ref();
688 Creates a copy of \a other.
690 QSqlDatabase::QSqlDatabase(const QSqlDatabase &other)
692 d = other.d;
693 d->ref.ref();
697 Assigns \a other to this object.
699 QSqlDatabase &QSqlDatabase::operator=(const QSqlDatabase &other)
701 qAtomicAssign(d, other.d);
702 return *this;
706 \internal
708 Create the actual driver instance \a type.
711 void QSqlDatabasePrivate::init(const QString &type)
713 drvName = type;
715 if (!driver) {
716 #ifdef QT_SQL_PSQL
717 if (type == QLatin1String("QPSQL") || type == QLatin1String("QPSQL7"))
718 driver = new QPSQLDriver();
719 #endif
720 #ifdef QT_SQL_MYSQL
721 if (type == QLatin1String("QMYSQL") || type == QLatin1String("QMYSQL3"))
722 driver = new QMYSQLDriver();
723 #endif
724 #ifdef QT_SQL_ODBC
725 if (type == QLatin1String("QODBC") || type == QLatin1String("QODBC3"))
726 driver = new QODBCDriver();
727 #endif
728 #ifdef QT_SQL_OCI
729 if (type == QLatin1String("QOCI") || type == QLatin1String("QOCI8"))
730 driver = new QOCIDriver();
731 #endif
732 #ifdef QT_SQL_TDS
733 if (type == QLatin1String("QTDS") || type == QLatin1String("QTDS7"))
734 driver = new QTDSDriver();
735 #endif
736 #ifdef QT_SQL_DB2
737 if (type == QLatin1String("QDB2"))
738 driver = new QDB2Driver();
739 #endif
740 #ifdef QT_SQL_SQLITE
741 if (type == QLatin1String("QSQLITE"))
742 driver = new QSQLiteDriver();
743 #endif
744 #ifdef QT_SQL_SQLITE2
745 if (type == QLatin1String("QSQLITE2"))
746 driver = new QSQLite2Driver();
747 #endif
748 #ifdef QT_SQL_IBASE
749 if (type == QLatin1String("QIBASE"))
750 driver = new QIBaseDriver();
751 #endif
754 if (!driver) {
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
771 if (!driver) {
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.
787 \sa close()
790 QSqlDatabase::~QSqlDatabase()
792 if (!d->ref.deref()) {
793 close();
794 delete d;
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()) {
811 r.exec(query);
812 d->driver->setLastError(r.lastError());
814 return r;
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);
833 \overload
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.
843 \sa lastError()
846 bool QSqlDatabase::open(const QString& user, const QString& password)
848 setUserName(user);
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
856 database.
858 This will also affect copies of this QSqlDatabase object.
860 \sa removeDatabase()
863 void QSqlDatabase::close()
865 d->driver->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))
899 return false;
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))
920 return false;
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))
941 return false;
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
952 object create time.
954 For the QOCI (Oracle) driver, the database name is the TNS
955 Service Name.
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)
975 if (isValid())
976 d->dbname = 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)
993 if (isValid())
994 d->uname = 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)
1015 if (isValid())
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)
1033 if (isValid())
1034 d->hname = 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)
1051 if (isValid())
1052 d->port = 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
1063 return d->dbname;
1067 Returns the connection's user name; it may be empty.
1069 \sa setUserName()
1071 QString QSqlDatabase::userName() const
1073 return d->uname;
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
1083 return d->pword;
1087 Returns the connection's host name; it may be empty.
1089 \sa setHostName()
1091 QString QSqlDatabase::hostName() const
1093 return d->hname;
1097 Returns the connection's driver name.
1099 \sa addDatabase(), driver()
1101 QString QSqlDatabase::driverName() const
1103 return d->drvName;
1107 Returns the connection's port number. The value is undefined if
1108 the port number has not been set.
1110 \sa setPort()
1112 int QSqlDatabase::port() const
1114 return d->port;
1118 Returns the database driver used to access the database
1119 connection.
1121 \sa addDatabase() drivers()
1124 QSqlDriver* QSqlDatabase::driver() const
1126 return d->driver;
1130 Returns information about the last error that occurred on the
1131 database.
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:
1192 \table
1193 \header \i ODBC \i MySQL \i PostgreSQL
1194 \row
1197 \list
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
1205 \i SQL_ATTR_TRACE
1206 \i SQL_ATTR_CONNECTION_POOLING
1207 \i SQL_ATTR_ODBC_VERSION
1208 \endlist
1211 \list
1212 \i CLIENT_COMPRESS
1213 \i CLIENT_FOUND_ROWS
1214 \i CLIENT_IGNORE_SPACE
1215 \i CLIENT_SSL
1216 \i CLIENT_ODBC
1217 \i CLIENT_NO_SCHEMA
1218 \i CLIENT_INTERACTIVE
1219 \i UNIX_SOCKET
1220 \endlist
1223 \list
1224 \i connect_timeout
1225 \i options
1226 \i tty
1227 \i requiressl
1228 \i service
1229 \endlist
1231 \header \i DB2 \i OCI \i TDS
1232 \row
1235 \list
1236 \i SQL_ATTR_ACCESS_MODE
1237 \i SQL_ATTR_LOGIN_TIMEOUT
1238 \endlist
1241 \list
1242 \i OCI_ATTR_PREFETCH_ROWS
1243 \i OCI_ATTR_PREFETCH_MEMORY
1244 \endlist
1247 \e none
1249 \header \i SQLite \i Interbase
1250 \row
1253 \list
1254 \i QSQLITE_BUSY_TIMEOUT
1255 \endlist
1258 \list
1259 \i ISC_DPB_LC_CTYPE
1260 \i ISC_DPB_SQL_ROLE_NAME
1261 \endlist
1263 \endtable
1265 Examples:
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)
1276 if (isValid())
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
1293 returns false.
1295 \sa drivers()
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
1314 \codeline
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:
1341 \table
1342 \header \i Driver \i Class name \i Constructor arguments \i File to include
1343 \row
1344 \i QPSQL
1345 \i QPSQLDriver
1346 \i PGconn *connection
1347 \i \c qsql_psql.cpp
1348 \row
1349 \i QMYSQL
1350 \i QMYSQLDriver
1351 \i MYSQL *connection
1352 \i \c qsql_mysql.cpp
1353 \row
1354 \i QOCI
1355 \i QOCIDriver
1356 \i OCIEnv *environment, OCISvcCtx *serviceContext
1357 \i \c qsql_oci.cpp
1358 \row
1359 \i QODBC
1360 \i QODBCDriver
1361 \i SQLHANDLE environment, SQLHANDLE connection
1362 \i \c qsql_odbc.cpp
1363 \row
1364 \i QDB2
1365 \i QDB2
1366 \i SQLHANDLE environment, SQLHANDLE connection
1367 \i \c qsql_db2.cpp
1368 \row
1369 \i QTDS
1370 \i QTDSDriver
1371 \i LOGINREC *loginRecord, DBPROCESS *dbProcess, const QString &hostName
1372 \i \c qsql_tds.cpp
1373 \row
1374 \i QSQLITE
1375 \i QSQLiteDriver
1376 \i sqlite *connection
1377 \i \c qsql_sqlite.cpp
1378 \row
1379 \i QIBASE
1380 \i QIBaseDriver
1381 \i isc_db_handle connection
1382 \i \c qsql_ibase.cpp
1383 \endtable
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
1388 simultaneously.
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
1396 removeDatabase().
1398 \sa drivers()
1400 QSqlDatabase QSqlDatabase::addDatabase(QSqlDriver* driver, const QString& connectionName)
1402 QSqlDatabase db(driver);
1403 QSqlDatabasePrivate::addDatabase(db, connectionName);
1404 return db;
1408 Returns true if the QSqlDatabase has a valid driver.
1410 Example:
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;
1418 #ifdef QT3_SUPPORT
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.
1436 #endif
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);
1456 return db;
1460 \since 4.4
1462 Returns the connection name, which may be empty. \note The
1463 connection name is not the \l{databaseName()} {database name}.
1465 \sa addDatabase()
1467 QString QSqlDatabase::connectionName() const
1469 return d->connName;
1472 #ifndef QT_NO_DEBUG_STREAM
1473 QDebug operator<<(QDebug dbg, const QSqlDatabase &d)
1475 if (!d.isValid()) {
1476 dbg.nospace() << "QSqlDatabase(invalid)";
1477 return dbg.space();
1480 dbg.nospace() << "QSqlDatabase(driver=\"" << d.driverName() << "\", database=\""
1481 << d.databaseName() << "\", host=\"" << d.hostName() << "\", port=" << d.port()
1482 << ", user=\"" << d.userName() << "\", open=" << d.isOpen() << ")";
1483 return dbg.space();
1485 #endif
1487 QT_END_NAMESPACE