Qt 4.8
Public Functions | Static Public Functions | Public Variables | Protected Functions | Properties | Friends | List of all members
QSqlDatabase Class Reference

The QSqlDatabase class represents a connection to a database. More...

#include <qsqldatabase.h>

Public Functions

void close ()
 Closes the database connection, freeing any resources acquired, and invalidating any existing QSqlQuery objects that are used with the database. More...
 
bool commit ()
 Commits a transaction to the database if the driver supports transactions and a transaction() has been started. More...
 
QString connectionName () const
 Returns the connection name, which may be empty. More...
 
QString connectOptions () const
 Returns the connection options string used for this connection. More...
 
QString databaseName () const
 Returns the connection's database name, which may be empty. More...
 
QSqlDriverdriver () const
 Returns the database driver used to access the database connection. More...
 
QString driverName () const
 Returns the connection's driver name. More...
 
QSqlQuery exec (const QString &query=QString()) const
 Executes a SQL statement on the database and returns a QSqlQuery object. More...
 
QString hostName () const
 Returns the connection's host name; it may be empty. More...
 
bool isOpen () const
 Returns true if the database connection is currently open; otherwise returns false. More...
 
bool isOpenError () const
 Returns true if there was an error opening the database connection; otherwise returns false. More...
 
bool isValid () const
 Returns true if the QSqlDatabase has a valid driver. More...
 
QSqlError lastError () const
 Returns information about the last error that occurred on the database. More...
 
QSql::NumericalPrecisionPolicy numericalPrecisionPolicy () const
 Returns the current default precision policy for the database connection. More...
 
bool open ()
 Opens the database connection using the current connection values. More...
 
bool open (const QString &user, const QString &password)
 Opens the database connection using the given user name and password. More...
 
QSqlDatabaseoperator= (const QSqlDatabase &other)
 Assigns other to this object. More...
 
QString password () const
 Returns the connection's password. More...
 
int port () const
 Returns the connection's port number. More...
 
QSqlIndex primaryIndex (const QString &tablename) const
 Returns the primary index for table tablename. More...
 
 QSqlDatabase ()
 Creates an empty, invalid QSqlDatabase object. More...
 
 QSqlDatabase (const QSqlDatabase &other)
 Creates a copy of other. More...
 
QSqlRecord record (const QString &tablename) const
 Returns a QSqlRecord populated with the names of all the fields in the table (or view) called tablename. More...
 
bool rollback ()
 Rolls back a transaction on the database, if the driver supports transactions and a transaction() has been started. More...
 
void setConnectOptions (const QString &options=QString())
 Sets database-specific options. More...
 
void setDatabaseName (const QString &name)
 Sets the connection's database name to name. More...
 
void setHostName (const QString &host)
 Sets the connection's host name to host. More...
 
void setNumericalPrecisionPolicy (QSql::NumericalPrecisionPolicy precisionPolicy)
 Sets the default numerical precision policy used by queries created on this database connection to precisionPolicy. More...
 
void setPassword (const QString &password)
 Sets the connection's password to password. More...
 
void setPort (int p)
 Sets the connection's port number to port. More...
 
void setUserName (const QString &name)
 Sets the connection's user name to name. More...
 
QStringList tables (QSql::TableType type=QSql::Tables) const
 Returns a list of the database's tables, system tables and views, as specified by the parameter type. More...
 
bool transaction ()
 Begins a transaction on the database if the driver supports transactions. More...
 
QString userName () const
 Returns the connection's user name; it may be empty. More...
 
 ~QSqlDatabase ()
 Destroys the object and frees any allocated resources. More...
 

Static Public Functions

static QSqlDatabase addDatabase (const QString &type, const QString &connectionName=QLatin1String(defaultConnection))
 Adds a database to the list of database connections using the driver type and the connection name connectionName. More...
 
static QSqlDatabase addDatabase (QSqlDriver *driver, const QString &connectionName=QLatin1String(defaultConnection))
 This overload is useful when you want to create a database connection with a driver you instantiated yourself. More...
 
static QSqlDatabase cloneDatabase (const QSqlDatabase &other, const QString &connectionName)
 Clones the database connection other and and stores it as connectionName. More...
 
static QStringList connectionNames ()
 Returns a list containing the names of all connections. More...
 
static bool contains (const QString &connectionName=QLatin1String(defaultConnection))
 Returns true if the list of database connections contains connectionName; otherwise returns false. More...
 
static QSqlDatabase database (const QString &connectionName=QLatin1String(defaultConnection), bool open=true)
 Returns the database connection called connectionName. More...
 
static QStringList drivers ()
 Returns a list of all the available database drivers. More...
 
static bool isDriverAvailable (const QString &name)
 Returns true if a driver called name is available; otherwise returns false. More...
 
static void registerSqlDriver (const QString &name, QSqlDriverCreatorBase *creator)
 This function registers a new SQL driver called name, within the SQL framework. More...
 
static void removeDatabase (const QString &connectionName)
 Removes the database connection connectionName from the list of database connections. More...
 

Public Variables

QT_STATIC_CONST char * defaultConnection
 

Protected Functions

 QSqlDatabase (const QString &type)
 Creates a QSqlDatabase connection that uses the driver referred to by type. More...
 
 QSqlDatabase (QSqlDriver *driver)
 Creates a database connection using the given driver. More...
 

Properties

QSqlDatabasePrivated
 

Friends

class QSqlDatabasePrivate
 

Detailed Description

The QSqlDatabase class represents a connection to a database.

Attention
Module: QtSql

The QSqlDatabase class provides an interface for accessing a database through a connection. An instance of QSqlDatabase represents the connection. The connection provides access to the database via one of the SQL Database Drivers::Supported Databases {supported database drivers}, which are derived from QSqlDriver. Alternatively, you can subclass your own database driver from QSqlDriver. See How to Write Your Own Database Driver for more information.

Create a connection (i.e., an instance of QSqlDatabase) by calling one of the static addDatabase() functions, where you specify SQL Database Drivers::Supported Databases {the driver or type of driver} to use (i.e., what kind of database will you access?) and a connection name. A connection is known by its own name, not by the name of the database it connects to. You can have multiple connections to one database. QSqlDatabase also supports the concept of a default connection, which is the unnamed connection. To create the default connection, don't pass the connection name argument when you call addDatabase(). Subsequently, when you call any static member function that takes the connection name argument, if you don't pass the connection name argument, the default connection is assumed. The following snippet shows how to create and open a default connection to a PostgreSQL database:

db.setHostName("acidalia");
db.setDatabaseName("customdb");
db.setUserName("mojito");
db.setPassword("J0a1m8");
bool ok = db.open();

Once the QSqlDatabase object has been created, set the connection parameters with setDatabaseName(), setUserName(), setPassword(), setHostName(), setPort(), and setConnectOptions(). Then call open() to activate the physical connection to the database. The connection is not usable until you open it.

The connection defined above will be the default connection, because we didn't give a connection name to QSqlDatabase::addDatabase() . Subsequently, you can get the default connection by calling database() without the connection name argument:

QSqlDatabase is a value class. Changes made to a database connection via one instance of QSqlDatabase will affect other instances of QSqlDatabase that represent the same connection. Use cloneDatabase() to create an independent database connection based on an existing one.

If you create multiple database connections, specify a unique connection name for each one, when you call addDatabase(). Use database() with a connection name to get that connection. Use removeDatabase() with a connection name to remove a connection. QSqlDatabase outputs a warning if you try to remove a connection referenced by other QSqlDatabase objects. Use contains() to see if a given connection name is in the list of connections.

Once a connection is established, you can call tables() to get the list of tables in the database, call primaryIndex() to get a table's primary index, and call record() to get meta-information about a table's fields (e.g., field names).

Note
QSqlDatabase::exec() is deprecated. Use QSqlQuery::exec() instead.

If the driver supports transactions, use transaction() to start a transaction, and commit() or rollback() to complete it. Use QSqlDriver::hasFeature() to ask if the driver supports transactions.

Note
When using transactions, you must start the transaction before you create your query.

If an error occurrs, lastError() will return information about it.

Get the names of the available SQL drivers with drivers(). Check for the presence of a particular driver with isDriverAvailable(). If you have created your own custom driver, you must register it with registerSqlDriver().

See also
QSqlDriver, QSqlQuery, {QtSql Module}, {Threads and the SQL Module}

Definition at line 78 of file qsqldatabase.h.

Constructors and Destructors

◆ QSqlDatabase() [1/4]

QSqlDatabase::QSqlDatabase ( )

Creates an empty, invalid QSqlDatabase object.

Use addDatabase(), removeDatabase(), and database() to get valid QSqlDatabase objects.

Definition at line 729 of file qsqldatabase.cpp.

730 {
732  d->ref.ref();
733 }
QSqlDatabasePrivate * d
Definition: qsqldatabase.h:150
bool ref()
Atomically increments the value of this QAtomicInt.
static QSqlDatabasePrivate * shared_null()

◆ QSqlDatabase() [2/4]

QSqlDatabase::QSqlDatabase ( const QSqlDatabase other)

Creates a copy of other.

Definition at line 738 of file qsqldatabase.cpp.

739 {
740  d = other.d;
741  d->ref.ref();
742 }
QSqlDatabasePrivate * d
Definition: qsqldatabase.h:150
bool ref()
Atomically increments the value of this QAtomicInt.

◆ ~QSqlDatabase()

QSqlDatabase::~QSqlDatabase ( )

Destroys the object and frees any allocated resources.

See also
close()

Definition at line 838 of file qsqldatabase.cpp.

839 {
840  if (!d->ref.deref()) {
841  close();
842  delete d;
843  }
844 }
void close()
Closes the database connection, freeing any resources acquired, and invalidating any existing QSqlQue...
QSqlDatabasePrivate * d
Definition: qsqldatabase.h:150
bool deref()
Atomically decrements the value of this QAtomicInt.

◆ QSqlDatabase() [3/4]

QSqlDatabase::QSqlDatabase ( const QString type)
explicitprotected

Creates a QSqlDatabase connection that uses the driver referred to by type.

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

If the type is not recognized, the database connection will have no functionality.

The currently available driver types are:

Driver Type Description
QDB2 IBM DB2
QIBASE Borland InterBase Driver
QMYSQL MySQL Driver
QOCI Oracle Call Interface Driver
QODBC ODBC Driver (includes Microsoft SQL Server)
QPSQL PostgreSQL Driver
QSQLITE SQLite version 3 or above
QSQLITE2 SQLite version 2
QTDS Sybase Adaptive Server

Additional third party drivers, including your own custom drivers, can be loaded dynamically.

See also
{SQL Database Drivers}, registerSqlDriver(), drivers()

Definition at line 704 of file qsqldatabase.cpp.

705 {
706  d = new QSqlDatabasePrivate(this);
707  d->init(type);
708 }
void init(const QString &type)
Create the actual driver instance type.
QSqlDatabasePrivate * d
Definition: qsqldatabase.h:150
friend class QSqlDatabasePrivate
Definition: qsqldatabase.h:149

◆ QSqlDatabase() [4/4]

QSqlDatabase::QSqlDatabase ( QSqlDriver driver)
explicitprotected

Creates a database connection using the given driver.

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Definition at line 719 of file qsqldatabase.cpp.

720 {
721  d = new QSqlDatabasePrivate(this, driver);
722 }
QSqlDatabasePrivate * d
Definition: qsqldatabase.h:150
friend class QSqlDatabasePrivate
Definition: qsqldatabase.h:149

Functions

◆ addDatabase() [1/2]

QSqlDatabase QSqlDatabase::addDatabase ( const QString type,
const QString connectionName = QLatin1String(defaultConnection) 
)
static

Adds a database to the list of database connections using the driver type and the connection name connectionName.

Note
This class or function is threadsafe.

If there already exists a database connection called connectionName, that connection is removed.

The database connection is referred to by connectionName. The newly added database connection is returned.

If type is not available or could not be loaded, isValid() returns false.

If connectionName is not specified, the new connection becomes the default connection for the application, and subsequent calls to database() without the connection name argument will return the default connection. If a connectionName is provided here, use database(connectionName) to retrieve the connection.

Warning
If you add a connection with the same name as an existing connection, the new connection replaces the old one. If you call this function more than once without specifying connectionName, the default connection will be the one replaced.

Before using the connection, it must be initialized. e.g., call some or all of setDatabaseName(), setUserName(), setPassword(), setHostName(), setPort(), and setConnectOptions(), and, finally, open().

See also
database() removeDatabase() {Threads and the SQL Module}

Definition at line 495 of file qsqldatabase.cpp.

Referenced by qmlsqldatabase_open_sync().

496 {
497  QSqlDatabase db(type);
498  QSqlDatabasePrivate::addDatabase(db, connectionName);
499  return db;
500 }
The QSqlDatabase class represents a connection to a database.
Definition: qsqldatabase.h:78
static void addDatabase(const QSqlDatabase &db, const QString &name)

◆ addDatabase() [2/2]

QSqlDatabase QSqlDatabase::addDatabase ( QSqlDriver driver,
const QString connectionName = QLatin1String(defaultConnection) 
)
static

This overload is useful when you want to create a database connection with a driver you instantiated yourself.

It might be your own database driver, or you might just need to instantiate one of the Qt drivers yourself. If you do this, it is recommended that you include the driver code in your application. For example, you can create a PostgreSQL connection with your own QPSQL driver like this:

#include "qtdir/src/sql/drivers/psql/qsql_psql.cpp"
PGconn *con = PQconnectdb("host=server user=bart password=simpson dbname=springfield");
QPSQLDriver *drv = new QPSQLDriver(con);
QSqlDatabase db = QSqlDatabase::addDatabase(drv); // becomes the new default connection
QSqlQuery query;
query.exec("SELECT NAME, ID FROM STAFF");
...

The above code sets up a PostgreSQL connection and instantiates a QPSQLDriver object. Next, addDatabase() is called to add the connection to the known connections so that it can be used by the Qt SQL classes. When a driver is instantiated with a connection handle (or set of handles), Qt assumes that you have already opened the database connection.

Note
We assume that qtdir is the directory where Qt is installed. This will pull in the code that is needed to use the PostgreSQL client library and to instantiate a QPSQLDriver object, assuming that you have the PostgreSQL headers somewhere in your include search path.

Remember that you must link your application against the database client library. Make sure the client library is in your linker's search path, and add lines like these to your .pro file:

unix:LIBS += -lpq
win32:LIBS += libpqdll.lib

The method described works for all the supplied drivers. The only difference will be in the driver constructor arguments. Here is a table of the drivers included with Qt, their source code files, and their constructor arguments:

Driver Class name Constructor arguments File to include
QPSQL QPSQLDriver PGconn *connection qsql_psql.cpp
QMYSQL QMYSQLDriver MYSQL *connection qsql_mysql.cpp
QOCI QOCIDriver OCIEnv *environment, OCISvcCtx *serviceContext qsql_oci.cpp
QODBC QODBCDriver SQLHANDLE environment, SQLHANDLE connection qsql_odbc.cpp
QDB2 QDB2 SQLHANDLE environment, SQLHANDLE connection qsql_db2.cpp
QTDS QTDSDriver LOGINREC *loginRecord, DBPROCESS *dbProcess, const QString &hostName qsql_tds.cpp
QSQLITE QSQLiteDriver sqlite *connection qsql_sqlite.cpp
QIBASE QIBaseDriver isc_db_handle connection qsql_ibase.cpp

The host name (or service name) is needed when constructing the QTDSDriver for creating new connections for internal queries. This is to prevent blocking when several QSqlQuery objects are used simultaneously.

Warning
Adding a database connection with the same connection name as an existing connection, causes the existing connection to be replaced by the new one.
The SQL framework takes ownership of the driver. It must not be deleted. To remove the connection, use removeDatabase().
See also
drivers()

Definition at line 1441 of file qsqldatabase.cpp.

1442 {
1443  QSqlDatabase db(driver);
1444  QSqlDatabasePrivate::addDatabase(db, connectionName);
1445  return db;
1446 }
The QSqlDatabase class represents a connection to a database.
Definition: qsqldatabase.h:78
static void addDatabase(const QSqlDatabase &db, const QString &name)

◆ cloneDatabase()

QSqlDatabase QSqlDatabase::cloneDatabase ( const QSqlDatabase other,
const QString connectionName 
)
static

Clones the database connection other and and stores it as connectionName.

All the settings from the original database, e.g. databaseName(), hostName(), etc., are copied across. Does nothing if other is an invalid database. Returns the newly created database connection.

Note
The new connection has not been opened. Before using the new connection, you must call open().

Definition at line 1492 of file qsqldatabase.cpp.

1493 {
1494  if (!other.isValid())
1495  return QSqlDatabase();
1496 
1497  QSqlDatabase db(other.driverName());
1498  db.d->copy(other.d);
1499  QSqlDatabasePrivate::addDatabase(db, connectionName);
1500  return db;
1501 }
void copy(const QSqlDatabasePrivate *other)
Copies the connection data from other.
QSqlDatabasePrivate * d
Definition: qsqldatabase.h:150
bool isValid() const
Returns true if the QSqlDatabase has a valid driver.
QSqlDatabase()
Creates an empty, invalid QSqlDatabase object.
The QSqlDatabase class represents a connection to a database.
Definition: qsqldatabase.h:78
static void addDatabase(const QSqlDatabase &db, const QString &name)
QString driverName() const
Returns the connection&#39;s driver name.

◆ close()

void QSqlDatabase::close ( )

Closes the database connection, freeing any resources acquired, and invalidating any existing QSqlQuery objects that are used with the database.

This will also affect copies of this QSqlDatabase object.

See also
removeDatabase()

Definition at line 914 of file qsqldatabase.cpp.

915 {
916  d->driver->close();
917 }
virtual void close()=0
Derived classes must reimplement this pure virtual function in order to close the database connection...
QSqlDatabasePrivate * d
Definition: qsqldatabase.h:150

◆ commit()

bool QSqlDatabase::commit ( )

Commits a transaction to the database if the driver supports transactions and a transaction() has been started.

Returns true if the operation succeeded. Otherwise it returns false.

Note
For some databases, the commit will fail and return false if there is an active query using the database for a SELECT. Make the query inactive before doing the commit.

Call lastError() to get information about errors.

See also
QSqlQuery::isActive() QSqlDriver::hasFeature() rollback()

Definition at line 967 of file qsqldatabase.cpp.

Referenced by qmlsqldatabase_change_version(), and qmlsqldatabase_transaction_shared().

968 {
970  return false;
971  return d->driver->commitTransaction();
972 }
virtual bool hasFeature(DriverFeature f) const =0
Returns true if the driver supports feature feature; otherwise returns false.
QSqlDatabasePrivate * d
Definition: qsqldatabase.h:150
virtual bool commitTransaction()
This function is called to commit a transaction.
Definition: qsqldriver.cpp:325

◆ connectionName()

QString QSqlDatabase::connectionName ( ) const

Returns the connection name, which may be empty.

Since
4.4
Note
The connection name is not the database name.
See also
addDatabase()

Definition at line 1514 of file qsqldatabase.cpp.

Referenced by qmlsqldatabase_change_version().

1515 {
1516  return d->connName;
1517 }
QSqlDatabasePrivate * d
Definition: qsqldatabase.h:150

◆ connectionNames()

QStringList QSqlDatabase::connectionNames ( )
static

Returns a list containing the names of all connections.

Note
This class or function is threadsafe.
See also
contains(), database(), {Threads and the SQL Module}

Definition at line 668 of file qsqldatabase.cpp.

Referenced by qmlsqldatabase_open_sync().

669 {
670  return dbDict()->keys_ts();
671 }

◆ connectOptions()

QString QSqlDatabase::connectOptions ( ) const

Returns the connection options string used for this connection.

The string may be empty.

See also
setConnectOptions()

Definition at line 1327 of file qsqldatabase.cpp.

1328 {
1329  return d->connOptions;
1330 }
QSqlDatabasePrivate * d
Definition: qsqldatabase.h:150

◆ contains()

bool QSqlDatabase::contains ( const QString connectionName = QLatin1String(defaultConnection))
static

Returns true if the list of database connections contains connectionName; otherwise returns false.

Note
This class or function is threadsafe.
See also
connectionNames(), database(), {Threads and the SQL Module}

Definition at line 653 of file qsqldatabase.cpp.

654 {
655  return dbDict()->contains_ts(connectionName);
656 }

◆ database()

QSqlDatabase QSqlDatabase::database ( const QString connectionName = QLatin1String(defaultConnection),
bool  open = true 
)
static

Returns the database connection called connectionName.

Note
This class or function is threadsafe.

The database connection must have been previously added with addDatabase(). If open is true (the default) and the database connection is not already open it is opened now. If no connectionName is specified the default connection is used. If connectionName does not exist in the list of databases, an invalid connection is returned.

See also
isOpen() {Threads and the SQL Module}

Definition at line 519 of file qsqldatabase.cpp.

Referenced by qInit(), qmlsqldatabase_open_sync(), and QSqlTableModel::QSqlTableModel().

520 {
521  return QSqlDatabasePrivate::database(connectionName, open);
522 }
static QSqlDatabase database(const QString &name, bool open)
bool open()
Opens the database connection using the current connection values.

◆ databaseName()

QString QSqlDatabase::databaseName ( ) const

Returns the connection's database name, which may be empty.

Note
The database name is not the connection name.
See also
setDatabaseName()

Definition at line 1107 of file qsqldatabase.cpp.

Referenced by operator<<().

1108 {
1109  return d->dbname;
1110 }
QSqlDatabasePrivate * d
Definition: qsqldatabase.h:150

◆ driver()

QSqlDriver * QSqlDatabase::driver ( ) const

Returns the database driver used to access the database connection.

See also
addDatabase() drivers()

Definition at line 1170 of file qsqldatabase.cpp.

Referenced by QSqlTableModelPrivate::exec(), QSqlTableModelPrivate::nameToIndex(), QRelation::populateDictionary(), and qInit().

1171 {
1172  return d->driver;
1173 }
QSqlDatabasePrivate * d
Definition: qsqldatabase.h:150

◆ driverName()

QString QSqlDatabase::driverName ( ) const

Returns the connection's driver name.

See also
addDatabase(), driver()

Definition at line 1147 of file qsqldatabase.cpp.

Referenced by cloneDatabase(), and operator<<().

1148 {
1149  return d->drvName;
1150 }
QSqlDatabasePrivate * d
Definition: qsqldatabase.h:150

◆ drivers()

QStringList QSqlDatabase::drivers ( )
static

Returns a list of all the available database drivers.

See also
registerSqlDriver()

Definition at line 565 of file qsqldatabase.cpp.

Referenced by QSqlDatabasePrivate::init().

566 {
567  QStringList list;
568 
569 #ifdef QT_SQL_PSQL
570  list << QLatin1String("QPSQL7");
571  list << QLatin1String("QPSQL");
572 #endif
573 #ifdef QT_SQL_MYSQL
574  list << QLatin1String("QMYSQL3");
575  list << QLatin1String("QMYSQL");
576 #endif
577 #ifdef QT_SQL_ODBC
578  list << QLatin1String("QODBC3");
579  list << QLatin1String("QODBC");
580 #endif
581 #ifdef QT_SQL_OCI
582  list << QLatin1String("QOCI8");
583  list << QLatin1String("QOCI");
584 #endif
585 #ifdef QT_SQL_TDS
586  list << QLatin1String("QTDS7");
587  list << QLatin1String("QTDS");
588 #endif
589 #ifdef QT_SQL_DB2
590  list << QLatin1String("QDB2");
591 #endif
592 #ifdef QT_SQL_SQLITE
593  list << QLatin1String("QSQLITE");
594 #endif
595 #ifdef QT_SQL_SQLITE2
596  list << QLatin1String("QSQLITE2");
597 #endif
598 #ifdef QT_SQL_IBASE
599  list << QLatin1String("QIBASE");
600 #endif
601 
602 #ifndef QT_NO_LIBRARY
603  if (QFactoryLoader *fl = loader()) {
604  QStringList keys = fl->keys();
605  for (QStringList::const_iterator i = keys.constBegin(); i != keys.constEnd(); ++i) {
606  if (!list.contains(*i))
607  list << *i;
608  }
609  }
610 #endif
611 
613  for (DriverDict::const_iterator i = dict.constBegin(); i != dict.constEnd(); ++i) {
614  if (!list.contains(i.key()))
615  list << i.key();
616  }
617 
618  return list;
619 }
const_iterator constBegin() const
Returns a const STL-style iterator pointing to the first item in the list.
Definition: qlist.h:269
QLatin1String(DBUS_INTERFACE_DBUS))) Q_GLOBAL_STATIC_WITH_ARGS(QString
Q_GLOBAL_STATIC_WITH_ARGS(QFactoryLoader, loader,(QSqlDriverFactoryInterface_iid, QLatin1String("/sqldrivers"))) QT_STATIC_CONST_IMPL char *QSqlDatabase typedef QHash< QString, QSqlDriverCreatorBase * > DriverDict
QStringList keys
friend class const_iterator
Definition: qlist.h:264
The QStringList class provides a list of strings.
Definition: qstringlist.h:66
QBool contains(const QString &str, Qt::CaseSensitivity cs=Qt::CaseSensitive) const
Returns true if the list contains the string str; otherwise returns false.
Definition: qstringlist.h:172
static DriverDict & driverDict()
const_iterator constEnd() const
Returns a const STL-style iterator pointing to the imaginary item after the last item in the list...
Definition: qlist.h:272

◆ exec()

QSqlQuery QSqlDatabase::exec ( const QString query = QString()) const

Executes a SQL statement on the database and returns a QSqlQuery object.

Use lastError() to retrieve error information. If query is empty, an empty, invalid query is returned and lastError() is not affected.

See also
QSqlQuery, lastError()

Definition at line 855 of file qsqldatabase.cpp.

856 {
858  if (!query.isEmpty()) {
859  r.exec(query);
860  d->driver->setLastError(r.lastError());
861  }
862  return r;
863 }
QSqlDatabasePrivate * d
Definition: qsqldatabase.h:150
The QSqlQuery class provides a means of executing and manipulating SQL statements.
Definition: qsqlquery.h:63
bool isEmpty() const
Returns true if the string has no characters; otherwise returns false.
Definition: qstring.h:704
virtual QSqlResult * createResult() const =0
Creates an empty SQL result on the database.
bool exec(const QString &query)
Executes the SQL in query.
Definition: qsqlquery.cpp:355
virtual void setLastError(const QSqlError &e)
This function is used to set the value of the last error, error, that occurred on the database...
Definition: qsqldriver.cpp:350

◆ hostName()

QString QSqlDatabase::hostName ( ) const

Returns the connection's host name; it may be empty.

See also
setHostName()

Definition at line 1137 of file qsqldatabase.cpp.

Referenced by operator<<().

1138 {
1139  return d->hname;
1140 }
QSqlDatabasePrivate * d
Definition: qsqldatabase.h:150

◆ isDriverAvailable()

bool QSqlDatabase::isDriverAvailable ( const QString name)
static

Returns true if a driver called name is available; otherwise returns false.

See also
drivers()

Definition at line 1339 of file qsqldatabase.cpp.

1340 {
1341  return drivers().contains(name);
1342 }
static QStringList drivers()
Returns a list of all the available database drivers.
QBool contains(const QString &str, Qt::CaseSensitivity cs=Qt::CaseSensitive) const
Returns true if the list contains the string str; otherwise returns false.
Definition: qstringlist.h:172

◆ isOpen()

bool QSqlDatabase::isOpen ( ) const

Returns true if the database connection is currently open; otherwise returns false.

Definition at line 924 of file qsqldatabase.cpp.

Referenced by QSqlDatabasePrivate::database(), operator<<(), and qmlsqldatabase_open_sync().

925 {
926  return d->driver->isOpen();
927 }
QSqlDatabasePrivate * d
Definition: qsqldatabase.h:150
virtual bool isOpen() const
Returns true if the database connection is open; otherwise returns false.
Definition: qsqldriver.cpp:182

◆ isOpenError()

bool QSqlDatabase::isOpenError ( ) const

Returns true if there was an error opening the database connection; otherwise returns false.

Error information can be retrieved using the lastError() function.

Definition at line 935 of file qsqldatabase.cpp.

936 {
937  return d->driver->isOpenError();
938 }
QSqlDatabasePrivate * d
Definition: qsqldatabase.h:150
bool isOpenError() const
Returns true if the there was an error opening the database connection; otherwise returns false...
Definition: qsqldriver.cpp:192

◆ isValid()

bool QSqlDatabase::isValid ( ) const

Returns true if the QSqlDatabase has a valid driver.

Example:

qDebug() << db.isValid(); // Returns false
db = QSqlDatabase::database("sales");
qDebug() << db.isValid(); // Returns true if "sales" connection exists
qDebug() << db.isValid(); // Returns false

Definition at line 1454 of file qsqldatabase.cpp.

Referenced by cloneDatabase(), QSqlDatabasePrivate::database(), operator<<(), qInit(), and QSqlTableModel::QSqlTableModel().

1455 {
1456  return d->driver && d->driver != d->shared_null()->driver;
1457 }
QSqlDatabasePrivate * d
Definition: qsqldatabase.h:150
static QSqlDatabasePrivate * shared_null()

◆ lastError()

QSqlError QSqlDatabase::lastError ( ) const

Returns information about the last error that occurred on the database.

Failures that occur in conjunction with an individual query are reported by QSqlQuery::lastError().

See also
QSqlError, QSqlQuery::lastError()

Definition at line 1185 of file qsqldatabase.cpp.

Referenced by QSqlDatabasePrivate::database().

1186 {
1187  return d->driver->lastError();
1188 }
QSqlDatabasePrivate * d
Definition: qsqldatabase.h:150
QSqlError lastError() const
Returns a QSqlError object which contains information about the last error that occurred on the datab...
Definition: qsqldriver.cpp:360

◆ numericalPrecisionPolicy()

QSql::NumericalPrecisionPolicy QSqlDatabase::numericalPrecisionPolicy ( ) const

Returns the current default precision policy for the database connection.

Since
4.6
See also
QSql::NumericalPrecisionPolicy, setNumericalPrecisionPolicy(), QSqlQuery::numericalPrecisionPolicy(), QSqlQuery::setNumericalPrecisionPolicy()

Definition at line 1557 of file qsqldatabase.cpp.

1558 {
1559  if(driver())
1560  return driver()->numericalPrecisionPolicy();
1561  else
1562  return d->precisionPolicy;
1563 }
QSqlDatabasePrivate * d
Definition: qsqldatabase.h:150
QSql::NumericalPrecisionPolicy precisionPolicy
QSqlDriver * driver() const
Returns the database driver used to access the database connection.
QSql::NumericalPrecisionPolicy numericalPrecisionPolicy() const
Returns the current default precision policy for the database connection.
Definition: qsqldriver.cpp:987

◆ open() [1/2]

bool QSqlDatabase::open ( )

Opens the database connection using the current connection values.

Returns true on success; otherwise returns false. Error information can be retrieved using lastError().

See also
lastError() setDatabaseName() setUserName() setPassword()
setHostName() setPort() setConnectOptions()

Definition at line 874 of file qsqldatabase.cpp.

Referenced by QSqlDatabasePrivate::database(), and qmlsqldatabase_open_sync().

875 {
876  return d->driver->open(d->dbname, d->uname, d->pword, d->hname,
877  d->port, d->connOptions);
878 }
QSqlDatabasePrivate * d
Definition: qsqldatabase.h:150
virtual bool open(const QString &db, const QString &user=QString(), const QString &password=QString(), const QString &host=QString(), int port=-1, const QString &connOpts=QString())=0
Derived classes must reimplement this pure virtual function to open a database connection on database...

◆ open() [2/2]

bool QSqlDatabase::open ( const QString user,
const QString password 
)

Opens the database connection using the given user name and password.

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Returns true on success; otherwise returns false. Error information can be retrieved using the lastError() function.

This function does not store the password it is given. Instead, the password is passed directly to the driver for opening the connection and it is then discarded.

See also
lastError()

Definition at line 897 of file qsqldatabase.cpp.

898 {
899  setUserName(user);
900  return d->driver->open(d->dbname, user, password, d->hname,
901  d->port, d->connOptions);
902 }
QSqlDatabasePrivate * d
Definition: qsqldatabase.h:150
virtual bool open(const QString &db, const QString &user=QString(), const QString &password=QString(), const QString &host=QString(), int port=-1, const QString &connOpts=QString())=0
Derived classes must reimplement this pure virtual function to open a database connection on database...
void setUserName(const QString &name)
Sets the connection&#39;s user name to name.

◆ operator=()

QSqlDatabase & QSqlDatabase::operator= ( const QSqlDatabase other)

Assigns other to this object.

Definition at line 747 of file qsqldatabase.cpp.

748 {
749  qAtomicAssign(d, other.d);
750  return *this;
751 }
QSqlDatabasePrivate * d
Definition: qsqldatabase.h:150
void qAtomicAssign(T *&d, T *x)
This is a helper for the assignment operators of implicitly shared classes.
Definition: qatomic.h:195

◆ password()

QString QSqlDatabase::password ( ) const

Returns the connection's password.

If the password was not set with setPassword(), and if the password was given in the open() call, or if no password was used, an empty string is returned.

Definition at line 1127 of file qsqldatabase.cpp.

1128 {
1129  return d->pword;
1130 }
QSqlDatabasePrivate * d
Definition: qsqldatabase.h:150

◆ port()

int QSqlDatabase::port ( ) const

Returns the connection's port number.

The value is undefined if the port number has not been set.

See also
setPort()

Definition at line 1158 of file qsqldatabase.cpp.

Referenced by operator<<().

1159 {
1160  return d->port;
1161 }
QSqlDatabasePrivate * d
Definition: qsqldatabase.h:150

◆ primaryIndex()

QSqlIndex QSqlDatabase::primaryIndex ( const QString tablename) const

Returns the primary index for table tablename.

If no primary index exists an empty QSqlIndex is returned.

See also
tables(), record()

Definition at line 1210 of file qsqldatabase.cpp.

Referenced by QSqlTableModelPrivate::initRecordAndPrimaryIndex().

1211 {
1212  return d->driver->primaryIndex(tablename);
1213 }
virtual QSqlIndex primaryIndex(const QString &tableName) const
Returns the primary index for table tableName.
Definition: qsqldriver.cpp:387
QSqlDatabasePrivate * d
Definition: qsqldatabase.h:150

◆ record()

QSqlRecord QSqlDatabase::record ( const QString tablename) const

Returns a QSqlRecord populated with the names of all the fields in the table (or view) called tablename.

The order in which the fields appear in the record is undefined. If no such table (or view) exists, an empty record is returned.

Definition at line 1223 of file qsqldatabase.cpp.

Referenced by QSqlTableModelPrivate::initRecordAndPrimaryIndex(), isValid(), and QSqlRelationalTableModel::selectStatement().

1224 {
1225  return d->driver->record(tablename);
1226 }
QSqlDatabasePrivate * d
Definition: qsqldatabase.h:150
virtual QSqlRecord record(const QString &tableName) const
Returns a QSqlRecord populated with the names of the fields in table tableName.
Definition: qsqldriver.cpp:399

◆ registerSqlDriver()

void QSqlDatabase::registerSqlDriver ( const QString name,
QSqlDriverCreatorBase creator 
)
static

This function registers a new SQL driver called name, within the SQL framework.

This is useful if you have a custom SQL driver and don't want to compile it as a plugin.

Example:

QSqlDatabase takes ownership of the creator pointer, so you mustn't delete it yourself.

See also
drivers()

Definition at line 634 of file qsqldatabase.cpp.

635 {
636  delete QSqlDatabasePrivate::driverDict().take(name);
637  if (creator)
638  QSqlDatabasePrivate::driverDict().insert(name, creator);
639 }
static DriverDict & driverDict()

◆ removeDatabase()

void QSqlDatabase::removeDatabase ( const QString connectionName)
static

Removes the database connection connectionName from the list of database connections.

Note
This class or function is threadsafe.
Warning
There should be no open queries on the database connection when this function is called, otherwise a resource leak will occur.

Example:

// WRONG
QSqlQuery query("SELECT NAME, DOB FROM EMPLOYEES", db);
QSqlDatabase::removeDatabase("sales"); // will output a warning
// "db" is now a dangling invalid database connection,
// "query" contains an invalid result set

The correct way to do it:

{
QSqlQuery query("SELECT NAME, DOB FROM EMPLOYEES", db);
}
// Both "db" and "query" are destroyed because they are out of scope
QSqlDatabase::removeDatabase("sales"); // correct

To remove the default connection, which may have been created with a call to addDatabase() not specifying a connection name, you can retrieve the default connection name by calling connectionName() on the database returned by database(). Note that if a default database hasn't been created an invalid database will be returned.

See also
database() connectionName() {Threads and the SQL Module}

Definition at line 554 of file qsqldatabase.cpp.

555 {
556  QSqlDatabasePrivate::removeDatabase(connectionName);
557 }
static void removeDatabase(const QString &name)

◆ rollback()

bool QSqlDatabase::rollback ( )

Rolls back a transaction on the database, if the driver supports transactions and a transaction() has been started.

Returns true if the operation succeeded. Otherwise it returns false.

Note
For some databases, the rollback will fail and return false if there is an active query using the database for a SELECT. Make the query inactive before doing the rollback.

Call lastError() to get information about errors.

See also
QSqlQuery::isActive() QSqlDriver::hasFeature() commit()

Definition at line 988 of file qsqldatabase.cpp.

Referenced by qmlsqldatabase_change_version(), and qmlsqldatabase_transaction_shared().

989 {
991  return false;
992  return d->driver->rollbackTransaction();
993 }
virtual bool rollbackTransaction()
This function is called to rollback a transaction.
Definition: qsqldriver.cpp:338
virtual bool hasFeature(DriverFeature f) const =0
Returns true if the driver supports feature feature; otherwise returns false.
QSqlDatabasePrivate * d
Definition: qsqldatabase.h:150

◆ setConnectOptions()

void QSqlDatabase::setConnectOptions ( const QString options = QString())

Sets database-specific options.

This must be done before the connection is opened or it has no effect (or you can close() the connection, call this function and open() the connection again).

The format of the options string is a semicolon separated list of option names or option=value pairs. The options depend on the database client used:

ODBC MySQL PostgreSQL
SQL_ATTR_ACCESS_MODE SQL_ATTR_LOGIN_TIMEOUT SQL_ATTR_CONNECTION_TIMEOUT SQL_ATTR_CURRENT_CATALOG SQL_ATTR_METADATA_ID SQL_ATTR_PACKET_SIZE SQL_ATTR_TRACEFILE SQL_ATTR_TRACE SQL_ATTR_CONNECTION_POOLING

SQL_ATTR_ODBC_VERSION

CLIENT_COMPRESS CLIENT_FOUND_ROWS CLIENT_IGNORE_SPACE CLIENT_SSL CLIENT_ODBC CLIENT_NO_SCHEMA CLIENT_INTERACTIVE UNIX_SOCKET

MYSQL_OPT_RECONNECT

connect_timeout options tty requiressl

service

DB2 OCI TDS
SQL_ATTR_ACCESS_MODE

SQL_ATTR_LOGIN_TIMEOUT

OCI_ATTR_PREFETCH_ROWS

OCI_ATTR_PREFETCH_MEMORY

none

SQLite Interbase
QSQLITE_BUSY_TIMEOUT QSQLITE_OPEN_READONLY

QSQLITE_ENABLE_SHARED_CACHE

ISC_DPB_LC_CTYPE

ISC_DPB_SQL_ROLE_NAME

Examples:

...
// MySQL connection
db.setConnectOptions("CLIENT_SSL=1;CLIENT_IGNORE_SPACE=1"); // use an SSL connection to the server
if (!db.open()) {
db.setConnectOptions(); // clears the connect option string
...
}
...
// PostgreSQL connection
db.setConnectOptions("requiressl=1"); // enable PostgreSQL SSL connections
if (!db.open()) {
db.setConnectOptions(); // clear options
...
}
...
// ODBC connection
db.setConnectOptions("SQL_ATTR_ACCESS_MODE=SQL_MODE_READ_ONLY;SQL_ATTR_TRACE=SQL_OPT_TRACE_ON"); // set ODBC options
if (!db.open()) {
db.setConnectOptions(); // don't try to set this option
...
}

Refer to the client library documentation for more information about the different options.

See also
connectOptions()

Definition at line 1315 of file qsqldatabase.cpp.

1316 {
1317  if (isValid())
1318  d->connOptions = options;
1319 }
QSqlDatabasePrivate * d
Definition: qsqldatabase.h:150
bool isValid() const
Returns true if the QSqlDatabase has a valid driver.

◆ setDatabaseName()

void QSqlDatabase::setDatabaseName ( const QString name)

Sets the connection's database name to name.

To have effect, the database name must be set before the connection is opened. Alternatively, you can close() the connection, set the database name, and call open() again.

Note
The database name is not the connection name. The connection name must be passed to addDatabase() at connection object create time.

For the QOCI (Oracle) driver, the database name is the TNS Service Name.

For the QODBC driver, the name can either be a DSN, a DSN filename (in which case the file must have a .dsn extension), or a connection string.

For example, Microsoft Access users can use the following connection string to open an .mdb file directly, instead of having to create a DSN entry in the ODBC manager:

...
db.setDatabaseName("DRIVER={Microsoft Access Driver (*.mdb)};FIL={MS Access};DBQ=myaccessfile.mdb");
if (db.open()) {
// success!
}
...

There is no default value.

See also
databaseName() setUserName() setPassword() setHostName()
setPort() setConnectOptions() open()

Definition at line 1023 of file qsqldatabase.cpp.

Referenced by qmlsqldatabase_open_sync().

1024 {
1025  if (isValid())
1026  d->dbname = name;
1027 }
QSqlDatabasePrivate * d
Definition: qsqldatabase.h:150
bool isValid() const
Returns true if the QSqlDatabase has a valid driver.
const char * name

◆ setHostName()

void QSqlDatabase::setHostName ( const QString host)

Sets the connection's host name to host.

To have effect, the host name must be set before the connection is opened. Alternatively, you can close() the connection, set the host name, and call open() again.

There is no default value.

See also
hostName() setUserName() setPassword() setDatabaseName()
setPort() setConnectOptions() open()

Definition at line 1078 of file qsqldatabase.cpp.

1079 {
1080  if (isValid())
1081  d->hname = host;
1082 }
QSqlDatabasePrivate * d
Definition: qsqldatabase.h:150
bool isValid() const
Returns true if the QSqlDatabase has a valid driver.

◆ setNumericalPrecisionPolicy()

void QSqlDatabase::setNumericalPrecisionPolicy ( QSql::NumericalPrecisionPolicy  precisionPolicy)

Sets the default numerical precision policy used by queries created on this database connection to precisionPolicy.

Since
4.6

Note: Drivers that don't support fetching numerical values with low precision will ignore the precision policy. You can use QSqlDriver::hasFeature() to find out whether a driver supports this feature.

Note: Setting the default precision policy to precisionPolicy doesn't affect any currently active queries.

See also
QSql::NumericalPrecisionPolicy, numericalPrecisionPolicy(), QSqlQuery::setNumericalPrecisionPolicy(), QSqlQuery::numericalPrecisionPolicy()

Definition at line 1539 of file qsqldatabase.cpp.

1540 {
1541  if(driver())
1542  driver()->setNumericalPrecisionPolicy(precisionPolicy);
1543  d->precisionPolicy = precisionPolicy;
1544 }
QSqlDatabasePrivate * d
Definition: qsqldatabase.h:150
QSql::NumericalPrecisionPolicy precisionPolicy
void setNumericalPrecisionPolicy(QSql::NumericalPrecisionPolicy precisionPolicy)
Sets the default numerical precision policy used by queries created by this driver to precisionPolicy...
Definition: qsqldriver.cpp:971
QSqlDriver * driver() const
Returns the database driver used to access the database connection.

◆ setPassword()

void QSqlDatabase::setPassword ( const QString password)

Sets the connection's password to password.

To have effect, the password must be set before the connection is opened. Alternatively, you can close() the connection, set the password, and call open() again.

There is no default value.

Warning
This function stores the password in plain text within Qt. Use the open() call that takes a password as parameter to avoid this behavior.
See also
password() setUserName() setDatabaseName() setHostName()
setPort() setConnectOptions() open()

Definition at line 1061 of file qsqldatabase.cpp.

1062 {
1063  if (isValid())
1064  d->pword = password;
1065 }
QSqlDatabasePrivate * d
Definition: qsqldatabase.h:150
bool isValid() const
Returns true if the QSqlDatabase has a valid driver.
QString password() const
Returns the connection&#39;s password.

◆ setPort()

void QSqlDatabase::setPort ( int  port)

Sets the connection's port number to port.

To have effect, the port number must be set before the connection is opened. Alternatively, you can close() the connection, set the port number, and call open() again..

There is no default value.

See also
port() setUserName() setPassword() setHostName()
setDatabaseName() setConnectOptions() open()

Definition at line 1095 of file qsqldatabase.cpp.

1096 {
1097  if (isValid())
1098  d->port = port;
1099 }
QSqlDatabasePrivate * d
Definition: qsqldatabase.h:150
bool isValid() const
Returns true if the QSqlDatabase has a valid driver.
int port() const
Returns the connection&#39;s port number.

◆ setUserName()

void QSqlDatabase::setUserName ( const QString name)

Sets the connection's user name to name.

To have effect, the user name must be set before the connection is opened. Alternatively, you can close() the connection, set the user name, and call open() again.

There is no default value.

See also
userName() setDatabaseName() setPassword() setHostName()
setPort() setConnectOptions() open()

Definition at line 1040 of file qsqldatabase.cpp.

1041 {
1042  if (isValid())
1043  d->uname = name;
1044 }
QSqlDatabasePrivate * d
Definition: qsqldatabase.h:150
bool isValid() const
Returns true if the QSqlDatabase has a valid driver.
const char * name

◆ tables()

QStringList QSqlDatabase::tables ( QSql::TableType  type = QSql::Tables) const

Returns a list of the database's tables, system tables and views, as specified by the parameter type.

See also
primaryIndex(), record()

Definition at line 1198 of file qsqldatabase.cpp.

1199 {
1200  return d->driver->tables(type);
1201 }
int type
Definition: qmetatype.cpp:239
virtual QStringList tables(QSql::TableType tableType) const
Returns a list of the names of the tables in the database.
Definition: qsqldriver.cpp:376
QSqlDatabasePrivate * d
Definition: qsqldatabase.h:150

◆ transaction()

bool QSqlDatabase::transaction ( )

Begins a transaction on the database if the driver supports transactions.

Returns true if the operation succeeded. Otherwise it returns false.

See also
QSqlDriver::hasFeature(), commit(), rollback()

Definition at line 947 of file qsqldatabase.cpp.

Referenced by qmlsqldatabase_change_version(), and qmlsqldatabase_transaction_shared().

948 {
950  return false;
951  return d->driver->beginTransaction();
952 }
virtual bool hasFeature(DriverFeature f) const =0
Returns true if the driver supports feature feature; otherwise returns false.
QSqlDatabasePrivate * d
Definition: qsqldatabase.h:150
virtual bool beginTransaction()
This function is called to begin a transaction.
Definition: qsqldriver.cpp:312

◆ userName()

QString QSqlDatabase::userName ( ) const

Returns the connection's user name; it may be empty.

See also
setUserName()

Definition at line 1117 of file qsqldatabase.cpp.

Referenced by operator<<().

1118 {
1119  return d->uname;
1120 }
QSqlDatabasePrivate * d
Definition: qsqldatabase.h:150

Friends and Related Functions

◆ QSqlDatabasePrivate

friend class QSqlDatabasePrivate
friend

Definition at line 149 of file qsqldatabase.h.

Properties

◆ d

QSqlDatabasePrivate* QSqlDatabase::d
private

◆ defaultConnection

QT_STATIC_CONST char* QSqlDatabase::defaultConnection

Definition at line 128 of file qsqldatabase.h.

Referenced by qInit().


The documentation for this class was generated from the following files: