
We bake cookies in your browser for a better experience. Using this site means that you consent.Read More
TheQSqlDatabase class represents a connection to a database.More...
| Header: | #include <QSqlDatabase> |
| QSqlDatabase() | |
| QSqlDatabase(const QSqlDatabase & other) | |
| ~QSqlDatabase() | |
| void | close() |
| bool | commit() |
| QString | connectOptions() const |
| QString | connectionName() const |
| QString | databaseName() const |
| QSqlDriver * | driver() const |
| QString | driverName() const |
| QSqlQuery | exec(const QString & query = QString()) const |
| QString | hostName() const |
| bool | isOpen() const |
| bool | isOpenError() const |
| bool | isValid() const |
| QSqlError | lastError() const |
| QSql::NumericalPrecisionPolicy | numericalPrecisionPolicy() const |
| bool | open() |
| bool | open(const QString & user, const QString & password) |
| QString | password() const |
| int | port() const |
| QSqlIndex | primaryIndex(const QString & tablename) const |
| QSqlRecord | record(const QString & tablename) const |
| bool | rollback() |
| void | setConnectOptions(const QString & options = QString()) |
| void | setDatabaseName(const QString & name) |
| void | setHostName(const QString & host) |
| void | setNumericalPrecisionPolicy(QSql::NumericalPrecisionPolicy precisionPolicy) |
| void | setPassword(const QString & password) |
| void | setPort(int port) |
| void | setUserName(const QString & name) |
| QStringList | tables(QSql::TableType type = QSql::Tables) const |
| bool | transaction() |
| QString | userName() const |
| QSqlDatabase & | operator=(const QSqlDatabase & other) |
| QSqlDatabase | addDatabase(const QString & type, const QString & connectionName = QLatin1String( defaultConnection )) |
| QSqlDatabase | addDatabase(QSqlDriver * driver, const QString & connectionName = QLatin1String( defaultConnection )) |
| QSqlDatabase | cloneDatabase(const QSqlDatabase & other, const QString & connectionName) |
| QStringList | connectionNames() |
| bool | contains(const QString & connectionName = QLatin1String( defaultConnection )) |
| QSqlDatabase | database(const QString & connectionName = QLatin1String( defaultConnection ), bool open = true) |
| QStringList | drivers() |
| bool | isDriverAvailable(const QString & name) |
| void | registerSqlDriver(const QString & name, QSqlDriverCreatorBase * creator) |
| void | removeDatabase(const QString & connectionName) |
| QSqlDatabase(const QString & type) | |
| QSqlDatabase(QSqlDriver * driver) |
TheQSqlDatabase class represents a connection to a database.
TheQSqlDatabase class provides an interface for accessing a database through a connection. An instance ofQSqlDatabase represents the connection. The connection provides access to the database via one of thesupported database drivers, which are derived fromQSqlDriver. Alternatively, you can subclass your own database driver fromQSqlDriver. SeeHow to Write Your Own Database Driver for more information.
Create a connection (i.e., an instance ofQSqlDatabase) by calling one of the staticaddDatabase() functions, where you specifythe 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 adefault connection, which is the unnamed connection. To create the default connection, don't pass the connection name argument when you calladdDatabase(). 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:
QSqlDatabase db=QSqlDatabase::addDatabase("QPSQL"); db.setHostName("acidalia"); db.setDatabaseName("customdb"); db.setUserName("mojito"); db.setPassword("J0a1m8"); bool ok= db.open();
Once theQSqlDatabase object has been created, set the connection parameters withsetDatabaseName(),setUserName(),setPassword(),setHostName(),setPort(), andsetConnectOptions(). Then callopen() to activate the physical connection to the database. The connection is not usable until you open it.
The connection defined above will be thedefault connection, because we didn't give a connection name toaddDatabase(). Subsequently, you can get the default connection by callingdatabase() without the connection name argument:
QSqlDatabase db=QSqlDatabase::database();
QSqlDatabase is a value class. Changes made to a database connection via one instance ofQSqlDatabase will affect other instances ofQSqlDatabase that represent the same connection. UsecloneDatabase() 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 calladdDatabase(). Usedatabase() with a connection name to get that connection. UseremoveDatabase() with a connection name to remove a connection.QSqlDatabase outputs a warning if you try to remove a connection referenced by otherQSqlDatabase objects. Usecontains() to see if a given connection name is in the list of connections.
Once a connection is established, you can calltables() to get the list of tables in the database, callprimaryIndex() to get a table's primary index, and callrecord() to get meta-information about a table's fields (e.g., field names).
Note:QSqlDatabase::exec() is deprecated. UseQSqlQuery::exec() instead.
If the driver supports transactions, usetransaction() to start a transaction, andcommit() orrollback() to complete it. UsehasFeature() 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 withdrivers(). Check for the presence of a particular driver withisDriverAvailable(). If you have created your own custom driver, you must register it withregisterSqlDriver().
See alsoQSqlDriver,QSqlQuery,QtSql Module, andThreads and the SQL Module.
Creates an empty, invalidQSqlDatabase object. UseaddDatabase(),removeDatabase(), anddatabase() to get validQSqlDatabase objects.
Creates a copy ofother.
[protected]QSqlDatabase::QSqlDatabase(constQString & type)This is an overloaded function.
Creates aQSqlDatabase connection that uses the driver referred to bytype. If thetype 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 alsoSQL Database Drivers,registerSqlDriver(), anddrivers().
[protected]QSqlDatabase::QSqlDatabase(QSqlDriver * driver)This is an overloaded function.
Creates a database connection using the givendriver.
Destroys the object and frees any allocated resources.
See alsoclose().
[static]QSqlDatabase QSqlDatabase::addDatabase(constQString & type, constQString & connectionName = QLatin1String( defaultConnection ))Adds a database to the list of database connections using the drivertype and the connection nameconnectionName. If there already exists a database connection calledconnectionName, that connection is removed.
The database connection is referred to byconnectionName. The newly added database connection is returned.
Iftype is not available or could not be loaded,isValid() returns false.
IfconnectionName is not specified, the new connection becomes the default connection for the application, and subsequent calls todatabase() without the connection name argument will return the default connection. If aconnectionName 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 specifyingconnectionName, the default connection will be the one replaced.
Before using the connection, it must be initialized. e.g., call some or all ofsetDatabaseName(),setUserName(),setPassword(),setHostName(),setPort(), andsetConnectOptions(), and, finally,open().
Note: This function isthread-safe.
See alsodatabase(),removeDatabase(), andThreads and the SQL Module.
[static]QSqlDatabase QSqlDatabase::addDatabase(QSqlDriver * driver, constQString & connectionName = QLatin1String( defaultConnection ))This overload is useful when you want to create a database connection with adriver 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=newQPSQLDriver(con);QSqlDatabase db=QSqlDatabase::addDatabase(drv);// becomes the new default connectionQSqlQuery 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 thatqtdir 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+=-lpqwin32: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, constQString &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 severalQSqlQuery 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.
Warning: The SQL framework takes ownership of thedriver. It must not be deleted. To remove the connection, useremoveDatabase().
See alsodrivers().
[static]QSqlDatabase QSqlDatabase::cloneDatabase(constQSqlDatabase & other, constQString & connectionName)Clones the database connectionother and and stores it asconnectionName. All the settings from the original database, e.g.databaseName(),hostName(), etc., are copied across. Does nothing ifother 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 callopen().
Closes the database connection, freeing any resources acquired, and invalidating any existingQSqlQuery objects that are used with the database.
This will also affect copies of thisQSqlDatabase object.
See alsoremoveDatabase().
Commits a transaction to the database if the driver supports transactions and atransaction() has been started. Returnstrue if the operation succeeded. Otherwise it returnsfalse.
Note:For some databases, the commit will fail and returnfalse if there is anactive query using the database for aSELECT. Make the queryinactive before doing the commit.
CalllastError() to get information about errors.
See alsoQSqlQuery::isActive(),QSqlDriver::hasFeature(), androllback().
Returns the connection options string used for this connection. The string may be empty.
See alsosetConnectOptions().
Returns the connection name, which may be empty.
Note:The connection name is not thedatabase name.
This function was introduced in Qt 4.4.
See alsoaddDatabase().
[static]QStringList QSqlDatabase::connectionNames()Returns a list containing the names of all connections.
Note: This function isthread-safe.
See alsocontains(),database(), andThreads and the SQL Module.
[static]bool QSqlDatabase::contains(constQString & connectionName = QLatin1String( defaultConnection ))Returns true if the list of database connections containsconnectionName; otherwise returns false.
Note: This function isthread-safe.
See alsoconnectionNames(),database(), andThreads and the SQL Module.
[static]QSqlDatabase QSqlDatabase::database(constQString & connectionName = QLatin1String( defaultConnection ),bool open = true)Returns the database connection calledconnectionName. The database connection must have been previously added withaddDatabase(). Ifopen is true (the default) and the database connection is not already open it is opened now. If noconnectionName is specified the default connection is used. IfconnectionName does not exist in the list of databases, an invalid connection is returned.
Note: This function isthread-safe.
See alsoisOpen() andThreads and the SQL Module.
Returns the connection's database name, which may be empty.
Note:The database name is not the connection name.
See alsosetDatabaseName().
Returns the database driver used to access the database connection.
See alsoaddDatabase() anddrivers().
Returns the connection's driver name.
See alsoaddDatabase() anddriver().
[static]QStringList QSqlDatabase::drivers()Returns a list of all the available database drivers.
See alsoregisterSqlDriver().
Executes a SQL statement on the database and returns aQSqlQuery object. UselastError() to retrieve error information. Ifquery is empty, an empty, invalid query is returned andlastError() is not affected.
See alsoQSqlQuery andlastError().
Returns the connection's host name; it may be empty.
See alsosetHostName().
[static]bool QSqlDatabase::isDriverAvailable(constQString & name)Returns true if a driver calledname is available; otherwise returns false.
See alsodrivers().
Returns true if the database connection is currently open; otherwise returns false.
Returns true if there was an error opening the database connection; otherwise returns false. Error information can be retrieved using thelastError() function.
Returns true if theQSqlDatabase has a valid driver.
Example:
QSqlDatabase db;qDebug()<< db.isValid();// Returns falsedb=QSqlDatabase::database("sales");qDebug()<< db.isValid();// Returns true if "sales" connection existsQSqlDatabase::removeDatabase("sales");qDebug()<< db.isValid();// Returns false
Returns information about the last error that occurred on the database.
Failures that occur in conjunction with an individual query are reported byQSqlQuery::lastError().
See alsoQSqlError andQSqlQuery::lastError().
Returns the current default precision policy for the database connection.
This function was introduced in Qt 4.6.
See alsoQSql::NumericalPrecisionPolicy,setNumericalPrecisionPolicy(),QSqlQuery::numericalPrecisionPolicy(), andQSqlQuery::setNumericalPrecisionPolicy().
Opens the database connection using the current connection values. Returns true on success; otherwise returns false. Error information can be retrieved usinglastError().
See alsolastError(),setDatabaseName(),setUserName(),setPassword(),setHostName(),setPort(), andsetConnectOptions().
This is an overloaded function.
Opens the database connection using the givenuser name andpassword. Returns true on success; otherwise returns false. Error information can be retrieved using thelastError() 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 alsolastError().
Returns the connection's password. If the password was not set withsetPassword(), and if the password was given in theopen() call, or if no password was used, an empty string is returned.
See alsosetPassword().
Returns the connection's port number. The value is undefined if the port number has not been set.
See alsosetPort().
Returns the primary index for tabletablename. If no primary index exists an emptyQSqlIndex is returned.
Returns aQSqlRecord populated with the names of all the fields in the table (or view) calledtablename. The order in which the fields appear in the record is undefined. If no such table (or view) exists, an empty record is returned.
[static]void QSqlDatabase::registerSqlDriver(constQString & name,QSqlDriverCreatorBase * creator)This function registers a new SQL driver calledname, 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::registerSqlDriver("MYDRIVER",newQSqlDriverCreator<MyDatabaseDriver>);QSqlDatabase db=QSqlDatabase::addDatabase("MYDRIVER");
QSqlDatabase takes ownership of thecreator pointer, so you mustn't delete it yourself.
See alsodrivers().
[static]void QSqlDatabase::removeDatabase(constQString & connectionName)Removes the database connectionconnectionName from the list of database connections.
Warning: There should be no open queries on the database connection when this function is called, otherwise a resource leak will occur.
Example:
// WRONGQSqlDatabase db=QSqlDatabase::database("sales");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:
{QSqlDatabase db=QSqlDatabase::database("sales");QSqlQuery query("SELECT NAME, DOB FROM EMPLOYEES", db);}// Both "db" and "query" are destroyed because they are out of scopeQSqlDatabase::removeDatabase("sales");// correctTo remove the default connection, which may have been created with a call toaddDatabase() not specifying a connection name, you can retrieve the default connection name by callingconnectionName() on the database returned bydatabase(). Note that if a default database hasn't been created an invalid database will be returned.
Note: This function isthread-safe.
See alsodatabase(),connectionName(), andThreads and the SQL Module.
Rolls back a transaction on the database, if the driver supports transactions and atransaction() has been started. Returnstrue if the operation succeeded. Otherwise it returnsfalse.
Note:For some databases, the rollback will fail and returnfalse if there is anactive query using the database for aSELECT. Make the queryinactive before doing the rollback.
CalllastError() to get information about errors.
See alsoQSqlQuery::isActive(),QSqlDriver::hasFeature(), andcommit().
Sets database-specificoptions. This must be done before the connection is opened or it has no effect (or you canclose() the connection, call this function andopen() the connection again).
The format of theoptions string is a semicolon separated list of option names or option=value pairs. The options depend on the database client used:
| ODBC | MySQL | PostgreSQL |
|---|---|---|
|
|
|
| DB2 | OCI | TDS |
|
| none |
| SQLite | Interbase | |
|
|
Examples:
...// MySQL connectiondb.setConnectOptions("CLIENT_SSL=1;CLIENT_IGNORE_SPACE=1");// use an SSL connection to the serverif (!db.open()) { db.setConnectOptions();// clears the connect option string...}...// PostgreSQL connectiondb.setConnectOptions("requiressl=1");// enable PostgreSQL SSL connectionsif (!db.open()) { db.setConnectOptions();// clear options...}...// ODBC connectiondb.setConnectOptions("SQL_ATTR_ACCESS_MODE=SQL_MODE_READ_ONLY;SQL_ATTR_TRACE=SQL_OPT_TRACE_ON");// set ODBC optionsif (!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 alsoconnectOptions().
Sets the connection's database name toname. To have effect, the database name must be setbefore the connection isopened. Alternatively, you canclose() the connection, set the database name, and callopen() again.
Note:Thedatabase name is not theconnection name. The connection name must be passed toaddDatabase() at connection object create time.
For the QOCI (Oracle) driver, the database name is the TNS Service Name.
For the QODBC driver, thename 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=QSqlDatabase::addDatabase("QODBC");db.setDatabaseName("DRIVER={Microsoft Access Driver (*.mdb)};FIL={MS Access};DBQ=myaccessfile.mdb");if (db.open()) {// success!}...
There is no default value.
See alsodatabaseName(),setUserName(),setPassword(),setHostName(),setPort(),setConnectOptions(), andopen().
Sets the connection's host name tohost. To have effect, the host name must be setbefore the connection isopened. Alternatively, you canclose() the connection, set the host name, and callopen() again.
There is no default value.
See alsohostName(),setUserName(),setPassword(),setDatabaseName(),setPort(),setConnectOptions(), andopen().
Sets the default numerical precision policy used by queries created on this database connection toprecisionPolicy.
Note: Drivers that don't support fetching numerical values with low precision will ignore the precision policy. You can useQSqlDriver::hasFeature() to find out whether a driver supports this feature.
Note: Setting the default precision policy toprecisionPolicy doesn't affect any currently active queries.
This function was introduced in Qt 4.6.
See alsoQSql::NumericalPrecisionPolicy,numericalPrecisionPolicy(),QSqlQuery::setNumericalPrecisionPolicy(), andQSqlQuery::numericalPrecisionPolicy().
Sets the connection's password topassword. To have effect, the password must be setbefore the connection isopened. Alternatively, you canclose() the connection, set the password, and callopen() again.
There is no default value.
Warning: This function stores the password in plain text within Qt. Use theopen() call that takes a password as parameter to avoid this behavior.
See alsopassword(),setUserName(),setDatabaseName(),setHostName(),setPort(),setConnectOptions(), andopen().
Sets the connection's port number toport. To have effect, the port number must be setbefore the connection isopened. Alternatively, you canclose() the connection, set the port number, and callopen() again..
There is no default value.
See alsoport(),setUserName(),setPassword(),setHostName(),setDatabaseName(),setConnectOptions(), andopen().
Sets the connection's user name toname. To have effect, the user name must be setbefore the connection isopened. Alternatively, you canclose() the connection, set the user name, and callopen() again.
There is no default value.
See alsouserName(),setDatabaseName(),setPassword(),setHostName(),setPort(),setConnectOptions(), andopen().
Returns a list of the database's tables, system tables and views, as specified by the parametertype.
See alsoprimaryIndex() andrecord().
Begins a transaction on the database if the driver supports transactions. Returnstrue if the operation succeeded. Otherwise it returnsfalse.
See alsoQSqlDriver::hasFeature(),commit(), androllback().
Returns the connection's user name; it may be empty.
See alsosetUserName().
Assignsother to this object.
© 2016 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of theGNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.