QSqlDatabase Class Reference

The QSqlDatabase class represents a connection to a database.

  1. #include <QSqlDatabase>

Detailed Description

The QSqlDatabase class represents a connection to a database.

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 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 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:

  1.     QSqlDatabase db = QSqlDatabase::addDatabase("QPSQL");
  2.     db.setHostName("acidalia");
  3.     db.setDatabaseName("customdb");
  4.     db.setUserName("mojito");
  5.     db.setPassword("J0a1m8");
  6.     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 addDatabase(). Subsequently, you can get the default connection by calling database() without the connection name argument:

  1.     QSqlDatabase db = QSqlDatabase::database();

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 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, and Threads and the SQL Module.

Public Functions

Toggle details QSqlDatabase

QSqlDatabaseQSqlDatabase () ()

Creates an empty, invalid QSqlDatabase object. Use addDatabase(), removeDatabase(), and database() to get valid QSqlDatabase objects.

Look up this member in the source code.

Toggle details QSqlDatabase

QSqlDatabaseQSqlDatabase ( const QSqlDatabase &other ) ( const QSqlDatabase &other )

Creates a copy of other.

Look up this member in the source code.

Toggle details QSqlDatabase

QSqlDatabaseQSqlDatabase ( const QString &type ) ( const QString &type )[protected]

This is an overloaded function.

Creates a QSqlDatabase connection that uses the driver referred to by type. If the type is not recognized, the database connection will have no functionality.

The currently available driver types are:

Driver TypeDescription
QDB2IBM DB2
QIBASEBorland InterBase Driver
QMYSQLMySQL Driver
QOCIOracle Call Interface Driver
QODBCODBC Driver (includes Microsoft SQL Server)
QPSQLPostgreSQL Driver
QSQLITESQLite version 3 or above
QSQLITE2SQLite version 2
QTDSSybase Adaptive Server

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

See also SQL Database Drivers, registerSqlDriver(), and drivers().

Look up this member in the source code.

Toggle details QSqlDatabase

QSqlDatabaseQSqlDatabase ( QSqlDriver *driver ) ( QSqlDriver *driver )[protected]

This is an overloaded function.

Creates a database connection using the given driver.

Look up this member in the source code.

Toggle details QSqlDatabase

~QSqlDatabase~QSqlDatabase () ()

Destroys the object and frees any allocated resources.

If this is the last QSqlDatabase object that uses a certain database connection, the database connection is automatically closed.

See also close().

Look up this member in the source code.

Toggle details QSqlDatabase QSqlDatabase

addDatabaseaddDatabase ( const QString &type , const QString &connectionName=QLatin1String( defaultConnection ) ...) ( 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. 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(), and Threads and the SQL Module.

Look up this member in the source code.

Toggle details QSqlDatabase QSqlDatabase

addDatabaseaddDatabase ( QSqlDriver *driver , const QString &connectionName=QLatin1String( defaultConnection ) ...) ( 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:

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

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:

  1. unix:LIBS += -lpq
  2. 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:

DriverClass nameConstructor argumentsFile to include
QPSQLQPSQLDriverPGconn *connection qsql_psql.cpp
QMYSQLQMYSQLDriverMYSQL *connection qsql_mysql.cpp
QOCIQOCIDriverOCIEnv *environment, OCISvcCtx *serviceContext qsql_oci.cpp
QODBCQODBCDriverSQLHANDLE environment, SQLHANDLE connection qsql_odbc.cpp
QDB2QDB2SQLHANDLE environment, SQLHANDLE connection qsql_db2.cpp
QTDSQTDSDriverLOGINREC *loginRecord, DBPROCESS *dbProcess, const QString &hostName qsql_tds.cpp
QSQLITEQSQLiteDriversqlite *connection qsql_sqlite.cpp
QIBASEQIBaseDriverisc_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.

Warning: The SQL framework takes ownership of the driver. It must not be deleted. To remove the connection, use removeDatabase().

See also drivers().

Look up this member in the source code.

Toggle details QSqlDatabase QSqlDatabase

cloneDatabasecloneDatabase ( const QSqlDatabase &other , const QString &connectionName ...) ( 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().

Look up this member in the source code.

Toggle details void QSqlDatabase

closeclose () ()

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().

Look up this member in the source code.

Toggle details bool QSqlDatabase

commitcommit () ()

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(), and rollback().

Look up this member in the source code.

Toggle details QString QSqlDatabase

connectOptionsconnectOptions () ()const

Returns the connection options string used for this connection. The string may be empty.

See also setConnectOptions().

Look up this member in the source code.

Toggle details QString QSqlDatabase

connectionNameconnectionName () ()const

Returns the connection name, which may be empty. Note: The connection name is not the database name.

See also addDatabase().

Look up this member in the source code.

Toggle details QStringList QSqlDatabase

connectionNamesconnectionNames () () [static]

Returns a list containing the names of all connections.

See also contains(), database(), and Threads and the SQL Module.

Look up this member in the source code.

Toggle details bool QSqlDatabase

containscontains ( const QString &connectionName=QLatin1String( defaultConnection ) ...) ( const QString &connectionName=QLatin1String( defaultConnection ) ) [static]

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

See also connectionNames(), database(), and Threads and the SQL Module.

Look up this member in the source code.

Toggle details QSqlDatabase QSqlDatabase

databasedatabase ( const QString &connectionName=QLatin1String( defaultConnection ) , bool open=true ...) ( const QString &connectionName=QLatin1String( defaultConnection ) , bool open=true ) [static]

Returns the database connection called connectionName. 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() and Threads and the SQL Module.

Look up this member in the source code.

Toggle details QString QSqlDatabase

databaseNamedatabaseName () ()const

Returns the connection's database name, which may be empty. Note: The database name is not the connection name.

See also setDatabaseName().

Look up this member in the source code.

Toggle details QSqlDriver * QSqlDatabase

driverdriver () ()const

Returns the database driver used to access the database connection.

See also addDatabase() and drivers().

Look up this member in the source code.

Toggle details QString QSqlDatabase

driverNamedriverName () ()const

Returns the connection's driver name.

See also addDatabase() and driver().

Look up this member in the source code.

Toggle details QStringList QSqlDatabase

driversdrivers () () [static]

Returns a list of all the available database drivers.

See also registerSqlDriver().

Look up this member in the source code.

Toggle details QSqlQuery QSqlDatabase

execexec ( const QString &query=QString() ) ( 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 and lastError().

Look up this member in the source code.

Toggle details QString QSqlDatabase

hostNamehostName () ()const

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

See also setHostName().

Look up this member in the source code.

Toggle details bool QSqlDatabase

isDriverAvailableisDriverAvailable ( const QString &name ) ( const QString &name ) [static]

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

See also drivers().

Look up this member in the source code.

Toggle details bool QSqlDatabase

isOpenisOpen () ()const

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

Look up this member in the source code.

Toggle details bool QSqlDatabase

isOpenErrorisOpenError () ()const

Returns true if there was an error opening the database connection; otherwise returns false. Error information can be retrieved using the lastError() function.

Look up this member in the source code.

Toggle details bool QSqlDatabase

isValidisValid () ()const

Returns true if the QSqlDatabase has a valid driver.

Example:

  1.                     QSqlDatabase db;
  2. qDebug() << db.isValid();    // Returns false
  3.  
  4. db = QSqlDatabase::database("sales");
  5. qDebug() << db.isValid();    // Returns true if "sales" connection exists
  6.  
  7. QSqlDatabase::removeDatabase("sales");
  8. qDebug() << db.isValid();    // Returns false

Look up this member in the source code.

Toggle details QSqlError QSqlDatabase

lastErrorlastError () ()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 and QSqlQuery::lastError().

Look up this member in the source code.

Toggle details QSql::NumericalPrecisionPolicy QSqlDatabase

numericalPrecisionPolicynumericalPrecisionPolicy (...) ()const

Returns the current default precision policy for the database connection.

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

Look up this member in the source code.

Toggle details bool QSqlDatabase

openopen () ()

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(), and setConnectOptions().

Look up this member in the source code.

Toggle details bool QSqlDatabase

openopen ( const QString &user , const QString &password ...) ( const QString &user , const QString &password )

This is an overloaded function.

Opens the database connection using the given user name and password. 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().

Look up this member in the source code.

Toggle details QString QSqlDatabase

passwordpassword () ()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.

See also setPassword().

Look up this member in the source code.

Toggle details int QSqlDatabase

portport () ()const

Returns the connection's port number. The value is undefined if the port number has not been set.

See also setPort().

Look up this member in the source code.

Toggle details QSqlIndex QSqlDatabase

primaryIndexprimaryIndex ( const QString &tablename ) ( const QString &tablename )const

Returns the primary index for table tablename. If no primary index exists an empty QSqlIndex is returned.

See also tables() and record().

Look up this member in the source code.

Toggle details QSqlRecord QSqlDatabase

recordrecord ( const QString &tablename ) ( 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.

Look up this member in the source code.

Toggle details void QSqlDatabase

registerSqlDriverregisterSqlDriver ( const QString &name , QSqlDriverCreatorBase *creator ...) ( 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:

  1.                     QSqlDatabase::registerSqlDriver("MYDRIVER",
  2.                                 new QSqlDriverCreator<MyDatabaseDriver>);
  3. QSqlDatabase db = QSqlDatabase::addDatabase("MYDRIVER");

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

See also drivers().

Look up this member in the source code.

Toggle details void QSqlDatabase

removeDatabaseremoveDatabase ( const QString &connectionName ( const QString &connectionName ) [static]

Removes the database connection connectionName 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:

  1. // WRONG
  2. QSqlDatabase db = QSqlDatabase::database("sales");
  3. QSqlQuery query("SELECT NAME, DOB FROM EMPLOYEES", db);
  4. QSqlDatabase::removeDatabase("sales"); // will output a warning
  5.  
  6. // "db" is now a dangling invalid database connection,
  7. // "query" contains an invalid result set

The correct way to do it:

  1.  {
  2.     QSqlDatabase db = QSqlDatabase::database("sales");
  3.     QSqlQuery query("SELECT NAME, DOB FROM EMPLOYEES", db);
  4. }
  5. // Both "db" and "query" are destroyed because they are out of scope
  6. 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(), and Threads and the SQL Module.

Look up this member in the source code.

Toggle details bool QSqlDatabase

rollbackrollback () ()

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(), and commit().

Look up this member in the source code.

Toggle details void QSqlDatabase

setConnectOptionssetConnectOptions ( const QString &options=QString() ...) ( 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:

ODBCMySQLPostgreSQL
  • 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
DB2OCITDS
  • SQL_ATTR_ACCESS_MODE
  • SQL_ATTR_LOGIN_TIMEOUT
  • OCI_ATTR_PREFETCH_ROWS
  • OCI_ATTR_PREFETCH_MEMORY
none
SQLiteInterbase
  • QSQLITE_BUSY_TIMEOUT
  • QSQLITE_OPEN_READONLY
  • QSQLITE_ENABLE_SHARED_CACHE
  • ISC_DPB_LC_CTYPE
  • ISC_DPB_SQL_ROLE_NAME

Examples:

  1. ...
  2. // MySQL connection
  3. db.setConnectOptions("CLIENT_SSL=1;CLIENT_IGNORE_SPACE=1"); // use an SSL connection to the server
  4. if (!db.open())  {
  5.     db.setConnectOptions(); // clears the connect option string
  6.     ...
  7. }
  8. ...
  9. // PostgreSQL connection
  10. db.setConnectOptions("requiressl=1"); // enable PostgreSQL SSL connections
  11. if (!db.open())  {
  12.     db.setConnectOptions(); // clear options
  13.     ...
  14. }
  15. ...
  16. // ODBC connection
  17. db.setConnectOptions("SQL_ATTR_ACCESS_MODE=SQL_MODE_READ_ONLY;SQL_ATTR_TRACE=SQL_OPT_TRACE_ON"); // set ODBC options
  18. if (!db.open())  {
  19.     db.setConnectOptions(); // don't try to set this option
  20.     ...
  21. }

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

See also connectOptions().

Look up this member in the source code.

Toggle details void QSqlDatabase

setDatabaseNamesetDatabaseName ( const QString &name ) ( 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:

  1. ...
  2. db = QSqlDatabase::addDatabase("QODBC");
  3. db.setDatabaseName("DRIVER= {Microsoft Access Driver (*.mdb)};FIL= {MS Access};DBQ=myaccessfile.mdb");
  4. if (db.open())  {
  5.     // success!
  6. }
  7. ...

There is no default value.

See also databaseName(), setUserName(), setPassword(), setHostName(), setPort(), setConnectOptions(), and open().

Look up this member in the source code.

Toggle details void QSqlDatabase

setHostNamesetHostName ( const QString &host ) ( 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(), and open().

Look up this member in the source code.

Toggle details void QSqlDatabase

setNumericalPrecisionPolicysetNumericalPrecisionPolicy ( QSql::NumericalPrecisionPolicy precisionPolicy ...) ( QSql::NumericalPrecisionPolicy precisionPolicy )

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

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(), and QSqlQuery::numericalPrecisionPolicy().

Look up this member in the source code.

Toggle details void QSqlDatabase

setPasswordsetPassword ( const QString &password ) ( 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(), and open().

Look up this member in the source code.

Toggle details void QSqlDatabase

setPortsetPort ( int port ) ( 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(), and open().

Look up this member in the source code.

Toggle details void QSqlDatabase

setUserNamesetUserName ( const QString &name ) ( 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(), and open().

Look up this member in the source code.

Toggle details QStringList QSqlDatabase

tablestables ( QSql::TableType type=QSql::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() and record().

Look up this member in the source code.

Toggle details bool QSqlDatabase

transactiontransaction () ()

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(), and rollback().

Look up this member in the source code.

Toggle details QString QSqlDatabase

userNameuserName () ()const

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

See also setUserName().

Look up this member in the source code.

Toggle details QSqlDatabase & QSqlDatabase

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

Assigns other to this object.

Look up this member in the source code.

Toggle details QSqlRecord QSqlDatabase

recordrecord ( const QSqlQuery &query ) ( const QSqlQuery &query )const Qt3-support

Use query.record() instead.

Look up this member in the source code.

Toggle details QSqlRecord QSqlDatabase

recordInforecordInfo ( const QString &tablename ) ( const QString &tablename )const Qt3-support

Use record() instead.

Look up this member in the source code.

Toggle details QSqlRecord QSqlDatabase

recordInforecordInfo ( const QSqlQuery &query ) ( const QSqlQuery &query )const Qt3-support

Use query.record() instead.

Look up this member in the source code.

Notes provided by the Qt Community
Informative
  • 5

Votes: 2

Coverage: Qt library 4.7, 4.8, 5.0

Picture of Lukas Geyer Lukas Geyer

Lab Rat
4 notes

QSqlDatabase::open() closes and re-opens existing database connections

Be aware that QSqlDatabase::open() will close and re-open an existing database connection. As closing [developer.qt.nokia.com] a database connection leads to … 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. … calling QSqlDatabase::open() on an already opened database connection will invalidate any active queries which is known to cause memory leaks.

Do not call QSqlDatabase::open() on already opened database connections or make sure all existing queries are gone out of scope or have been deactivated.

[Revisions]

Informative
  • 5

Votes: 1

Coverage: Qt library 4.7, Qt 4.8

Picture of Zark Zark

Lab Rat
4 notes

SQLite transactions are not safe in multi-threading environment out of the box

For the SQLite driver the function QSqlDatabase::transaction() starts the transaction with “BEGIN” which by default is the DEFERRED mode. For safe usage of transactions by multiple threads simultaneously one should manually start transaction with “BEGIN IMMEDIATE TRANSACTION” query. Furthermore one should use this mode whenever transactions are used across threads in the application. Read more on SQLite transaction types here: http://www.sqlite.org/lang_transaction.html [sqlite.org]

[Revisions]

Informative
  • 4

Votes: 4

Coverage: Qt library 4.7, 4.8, 5.0

Picture of Volker Volker

Ant Farmer
35 notes

Nokia Certified Qt Developer

SQLite/Borland Interbase: setDatabaseName() takes full path to database file

In case of SQLite (QSQLITE) and Borland Interbase (QIBASE) – and only there – setDatabaseName() takes the full path to the database file. It may be a single file name, in that case it is located in “the current directory”, or some relative or absolute path + file name.

To make it relative to your application binary, you can use something like this:

  1. QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
  2. QString dbPath = QCoreApplication::applicationDirPath() + "/MyDatabase.db";
  3. db.setDatabaseName(dbPath);
  4. if (!db.open()) {
  5.     // handle error here...
  6. }

setHostName(), setPort(), setUsername() and setPassword() do not have any effect on SQLite databases and should be avoided.

[Revisions]

Informative
  • 3

Votes: 1

Coverage: Qt library 4.7, 4.8, 5.0

Picture of Rahul Das Rahul Das

Robot Herder
7 notes

Note For Symbian Developers

void QSqlDatabase::setDatabaseName ( const QString & name ) on symbian shows various result. The separators are creating the trouble, even though forward or backward slashes are supposed to behave alike in Qt.

Converting separators to native form as follows with the help of QFileInfo class.

  1. QFileInfo fileInfo(fileName);
  2. ::setDatabaseName(QDir::toNativeSeparators(fileInfo.absoluteFilePath()));

[Revisions]

Informative
  • 1

Votes: 1

Coverage: Qt library 4.7, 4.8

Picture of Thanatos.jsse Thanatos.jsse

Lab Rat
1 note

Note for create SQL conection

Never use QSqlDatabase::addDatabase() for QSqlDatabase object created with new estament, if you do, you will have the following error:

  1. myDb->addDatabase("QPSQL");
  2. myDb->setHostName("acidalia");
  3. myDb->setDatabaseName("customdb");
  4. myDb->setUserName("mojito");
  5. myDb->setPassword("J0a1m8");
  6. qDebug() << QSqlDatabase::database().lastError().text();
  7. // "Driver not loaded Driver not loaded"

[Revisions]