CopperSpice API  1.9.1
QSqlDatabase Class Reference

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

Public Methods

 QSqlDatabase ()
 
 QSqlDatabase (const QSqlDatabase &other)
 
 ~QSqlDatabase ()
 
void close ()
 
bool commit ()
 
QString connectionName () const
 
QString connectOptions () const
 
QString databaseName () const
 
QSqlDriverdriver () 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)
 
QSqlDatabase & operator= (const QSqlDatabase &other)
 
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
 

Static Public Methods

static QSqlDatabase addDatabase (const QString &type, const QString &connectionName=defaultConnection)
 
static QSqlDatabase addDatabase (QSqlDriver *driver, const QString &connectionName=defaultConnection)
 
static QSqlDatabase cloneDatabase (const QSqlDatabase &other, const QString &connectionName)
 
static QStringList connectionNames ()
 
static bool contains (const QString &connectionName=defaultConnection)
 
static QSqlDatabase database (const QString &connectionName=defaultConnection, bool open=true)
 
static QStringList drivers ()
 
static bool isDriverAvailable (const QString &name)
 
static void registerSqlDriver (const QString &name, QSqlDriverCreatorBase *creator)
 
static void removeDatabase (const QString &connectionName)
 

Protected Methods

 QSqlDatabase (const QString &type)
 
 QSqlDatabase (QSqlDriver *driver)
 

Detailed Description

The QSqlDatabase class represents a connection to a database. It provides an interface for accessing a database through a connection. Each QSqlDatabase object represents one connection. The connection provides access to the database via one of the supported SQL Database Drivers, which inherit from QSqlDriver.

To create a new connection the addDatabase() method is used. If you are using one of the built in SQL Database Drivers, use the pass the name of the driver and the name of a database. There is another version of addDatabase() where you pass a QSQLDriver which was already instantiated and then name of a database.

You can inherit from QSqlDriver and write your own database driver. This new driver must be registered by calling registerSqlDringer(). Refer to SQL Database Drivers for a list of supported drivers.

Connections

A connection has two names, the name of the database and the name of the connection. The second parameter in the call to addDatabase() is a string and it is both the name of the database and the name of the connection. The setDatabaseName() method is used to change the name of the database without changing the name of the connection.

Having multiple connections to one database is supported. Changes made using one connection will affect other connections. Use cloneDatabase() to create an independent database connection based on an existing one. The second parameter in addDatabase() has a default value, which is called the default connection. The value for this default is "qt_sql_default_connection".

The following example shows how to create and open a default connection to a PostgreSQL database.

db.setHostName("example.com");
db.setDatabaseName("customDB");
db.setUserName("my_username");
db.setPassword("my_password");
bool ok = db.open();

Multiple Connections

When creating multiple database connections you must specify a unique connection name for each one. This is done using the second parameter in the call to addDatabase().

Pass the connection name to the database() method to retrieve the corresponding connection name. Use removeDatabase() and pass the connection name to remove a specific connection. The QSqlDatabase class will output a warning if you try to remove a connection which is being used by other QSqlDatabase object.

Other Methods

Use contains() to see if a given connection name is in the list of connections. Once a connection is opened call tables() to retrieve the list of tables in that database. The primaryIndex() method is used to obtain the primary key and record() is used to retrieve the meta information about the fields in the table.

If the driver supports transactions, then calling transaction() starts a transaction. The methods commit() or rollback() are used to complete the transaction. Use hasFeature() to query if the driver supports transactions. When using transactions, you must start the transaction before you create your query.

If an error occurs call the lastError() method to retrieve a description about what happened.

See also
QSqlDriver, QSqlQuery, Threads in SQL

Constructor & Destructor Documentation

QSqlDatabase::QSqlDatabase ( )

Creates an empty invalid QSqlDatabase object.

QSqlDatabase::QSqlDatabase ( const QSqlDatabase &  other)

Copy constructs a new QSqlDatabase from other.

QSqlDatabase::~QSqlDatabase ( )

Destroys the object and frees any allocated resources.

See also
close()
QSqlDatabase::QSqlDatabase ( const QString type)
explicitprotected

Creates a QSqlDatabase connection using the driver referred to by type. If the type is not recognized the database connection will have no functionality. The following is a list of the available SQL drivers in CopperSpice. Additional third party drivers, including your own custom drivers, can be loaded at run time.

Driver TypeDescription
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
QTDS Sybase Adaptive Server
See also
drivers(), registerSqlDriver(), SQL Database Drivers,
QSqlDatabase::QSqlDatabase ( QSqlDriver driver)
explicitprotected

Creates a database connection using the given driver.

Method Documentation

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

Adds a database to the list of database connections using the driver type and the connection name connectionName. If a connection already exists, with the given connectionName, the old connection is removed before the new connection is opened. This method returns new database connection. If the type is not available or could not be loaded the isValid() will return false.

If no connection name is passed the defaultConnection name is used. The value for this default is "qt_sql_default_connection".

Before a new connection can be used it must be initialized. Depending on the database this will require calling some combination of: setDatabaseName(), setUserName(), setPassword(), setHostName(), setPort(), and setConnectOptions(). Then call open() to actually interact with the tables in the database.

See also
database(), removeDatabase(), Threads in SQL
QSqlDatabase QSqlDatabase::addDatabase ( QSqlDriver driver,
const QString connectionName = defaultConnection 
)
static

When creating a database connection with a custom SQL driver, this method must be used to create the new connection. The following example shows how to create a connection using a custom implementation of an SQL driver.

MyCustomSQLDriver *driver = new MyCustomSQLDriver("myDBName");
db.open();
See also
drivers()
QSqlDatabase QSqlDatabase::cloneDatabase ( const QSqlDatabase &  other,
const QString connectionName 
)
static

Clones the database connection other and stores using the given connectionName. All of the settings from the original database are copied to this connection. This method does nothing if other is an invalid database. Returns the new connection.

The new connection will not be automatically opened. Before using the new connection, you must call open().

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 affect any other QSqlDatabase objects which were using the same connection.

See also
removeDatabase()
bool QSqlDatabase::commit ( )

Commits a transaction to the database if the driver supports transactions and the transaction() method was called prior to calling this method. Returns true if the operation succeeded, otherwise it returns false. For some databases calling this method will fail and return false if there is an active query using the database for a SELECT.

If an error occurs call the lastError() method to retrieve a description about what happened.

See also
rollback(), QSqlDriver::hasFeature(), QSqlQuery::isActive(),
QString QSqlDatabase::connectionName ( ) const

Returns the connection name which may be empty. The connection name may not be the same as the database name.

See also
addDatabase()
QStringList QSqlDatabase::connectionNames ( )
static

Returns a list containing the names of all connections.

See also
contains(), database(), Threads in SQL
QString QSqlDatabase::connectOptions ( ) const

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

See also
setConnectOptions()
bool QSqlDatabase::contains ( const QString connectionName = defaultConnection)
static

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

See also
connectionNames(), database(), Threads in SQL
QSqlDatabase QSqlDatabase::database ( const QString connectionName = defaultConnection,
bool  open = true 
)
static

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

See also
isOpen(), Threads in SQL
QString QSqlDatabase::databaseName ( ) const

Returns the name of the database, it may be empty. The database name may not be the same as the connection name.

See also
setDatabaseName()
QSqlDriver * QSqlDatabase::driver ( ) const

Returns the database driver used to access the database connection.

See also
addDatabase(), drivers()
QString QSqlDatabase::driverName ( ) const

Returns the driver name.

See also
addDatabase(), driver()
QStringList QSqlDatabase::drivers ( )
static

Returns a list of all the available database drivers.

See also
registerSqlDriver()
QSqlQuery QSqlDatabase::exec ( const QString query = QString()) const

Executes an SQL statement using the current database and returns an QSqlQuery object. If query is empty then an invalid query is returned and lastError() is not updated.

If an error occurs and the query was not empty, call the lastError() method to retrieve a description about what happened.

See also
QSqlQuery, lastError()
QString QSqlDatabase::hostName ( ) const

Returns the host name, it may be empty.

See also
setHostName()
bool QSqlDatabase::isDriverAvailable ( const QString name)
static

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

See also
drivers()
bool QSqlDatabase::isOpen ( ) const

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

bool QSqlDatabase::isOpenError ( ) const

Returns true if there was an error opening the database connection, otherwise returns false. If an error occurs call the lastError() method to retrieve a description about what happened.

bool QSqlDatabase::isValid ( ) const

Returns true if the QSqlDatabase has a valid driver.

qDebug() << db.isValid(); // Returns false
db = QSqlDatabase::database("sales");
qDebug() << db.isValid(); // Returns true if the "sales" connection exists
qDebug() << db.isValid(); // Returns false since the connection was removed
QSqlError QSqlDatabase::lastError ( ) const

Returns information about the last error which occurred on this database connection. Failures occurring in conjunction with a specific query are reported by QSqlQuery::lastError().

QSql::NumericalPrecisionPolicy QSqlDatabase::numericalPrecisionPolicy ( ) const
bool QSqlDatabase::open ( )

Opens the database connection using the current values. Returns true on success, otherwise returns false. If an error occurs call the lastError() method to retrieve a description about what happened.

See also
setDatabaseName(), setUserName(), setPassword(), setHostName(), setPort(), setConnectOptions()
bool QSqlDatabase::open ( const QString user,
const QString password 
)

Opens the database connection using the given user name and password. This method does not store the password. Instead, the password is passed directly to the driver for opening the connection and it is then discarded. Returns true on success, otherwise returns false. If an error occurs call the lastError() method to retrieve a description about what happened.

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

Copy assigns from other and returns a reference to this object.

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.

See also
setPassword()
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()
QSqlIndex QSqlDatabase::primaryIndex ( const QString tablename) const

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

See also
tables(), record()
QSqlRecord QSqlDatabase::record ( const QString tablename) const

Returns a QSqlRecord populated with the names of all the fields in the table (or view) with the given tablename. The order in which the fields appear in the record is not guaranteed. If no such table (or view) exists, an empty record is returned.

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

Registers a new SQL driver called name. This is useful if there is a custom SQL driver and it is not a plugin. The QSqlDatabase will take ownership of the object passed in the second parameter. You should never delete this object in your code.

See also
drivers()
void QSqlDatabase::removeDatabase ( const QString connectionName)
static

Removes the database connection with the given connectionName from the list of database connections. There should be no open queries on the database connection when this method is called.

The following example is incorrect. After the call to this method the variable db will be an invalid database connection and the query will contain an invalid result set.

QSqlQuery query("SELECT NAME, DOB FROM EMPLOYEES", db);
QSqlDatabase::removeDatabase("sales"); // will output a warning

The following example shows the correct way to call this method. By the time removeDatabase() is called both the variable db and the query will be out of scope.

{
QSqlQuery query("SELECT NAME, DOB FROM EMPLOYEES", db);
}
See also
database(), connectionName(), Threads in SQL
bool QSqlDatabase::rollback ( )

Rolls back a transaction on the database if the driver supports transactions and the transaction() method was called prior to calling this method. Returns true if the operation succeeded, otherwise it returns false. For some databases the rollback will fail and return false if there is an active query using the database for a SELECT.

If an error occurs call the lastError() method to retrieve a description about what happened.

See also
QSqlQuery::isActive(), QSqlDriver::hasFeature(), commit()
void QSqlDatabase::setConnectOptions ( const QString options = QString())

Sets various database parameters using the given options. This method must be called before the connection is opened or they will have no effect. The format of the options is a semicolon separated list of option names or option=value pairs.

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

MySQL PostgreSQL
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
ODBC SQLite
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
QSQLITE_BUSY_TIMEOUT
QSQLITE_OPEN_READONLY
QSQLITE_ENABLE_SHARED_CACHE
DB2 OCI
SQL_ATTR_ACCESS_MODE
SQL_ATTR_LOGIN_TIMEOUT
OCI_ATTR_PREFETCH_ROWS
OCI_ATTR_PREFETCH_MEMORY
Interbase TDS
ISC_DPB_LC_CTYPE
ISC_DPB_SQL_ROLE_NAME
none


// (1) MySQL connection
db.setConnectOptions("CLIENT_SSL=1;CLIENT_IGNORE_SPACE=1");
if (! db.open()) {
db.setConnectOptions(); // clears the connect option string
...
}
// (2) PostgreSQL connection
db.setConnectOptions("requiressl=1"); // enable PostgreSQL SSL connections
if (! db.open()) {
db.setConnectOptions(); // clear options
...
}
// (3) ODBC connection
db.setConnectOptions("SQL_ATTR_ACCESS_MODE=SQL_MODE_READ_ONLY;SQL_ATTR_TRACE=SQL_OPT_TRACE_ON");
if (! db.open()) {
db.setConnectOptions(); // do not try to set this option
// do something
}
See also
connectOptions()
void QSqlDatabase::setDatabaseName ( const QString name)

Sets the database name to the given name. The database name must be set before the connection is opened. The database name might not be the same as the connection name.

  • For SQLite if the name is the string ":memory:" then thd database will be stored in memory. When the connection is closed the database will cease to exist.
  • For the QOCI (Oracle) driver the 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.

As an example, the following code can be used to open a Microsoft Access .mdb file without 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()) {
// do something
}
See also
databaseName(), setUserName(), setPassword(), setHostName(), setPort(), setConnectOptions(), open()
void QSqlDatabase::setHostName ( const QString host)

Sets the connection's host name to host. The host name must be set before the connection is opened.

See also
hostName(), setUserName(), setPassword(), setDatabaseName(), setPort(), setConnectOptions(), open()
void QSqlDatabase::setNumericalPrecisionPolicy ( QSql::NumericalPrecisionPolicy  precisionPolicy)

Sets the default numerical precision policy used by queries created on this database connection to precisionPolicy. Drivers that do not support fetching numerical values with low precision will ignore the precision policy. The method QSqlDriver::hasFeature() can be used to find out whether a driver supports this feature.

Setting the default precision policy to precisionPolicy does not affect any currently active queries.

See also
QSql::NumericalPrecisionPolicy, numericalPrecisionPolicy(), QSqlQuery::setNumericalPrecisionPolicy(), QSqlQuery::numericalPrecisionPolicy()
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. The password is stored in plain text. Alternatively, supply the password in the call to open() so the password is never stored.

See also
password(), setUserName(), setDatabaseName(), setHostName(), setPort(), setConnectOptions(), open()
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.

See also
port(), setUserName(), setPassword(), setHostName(), setDatabaseName(), setConnectOptions(), open()
void QSqlDatabase::setUserName ( const QString name)

Sets the connection's user name to the given name. The user name must be set before the connection is opened.

See also
userName(), setDatabaseName(), setPassword(), setHostName(), setPort(), setConnectOptions(), open()
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()
bool QSqlDatabase::transaction ( )

Begins a transaction on the database if the SQL driver supports transactions. Returns true if the operation succeeded. Otherwise it returns false.

See also
commit(), rollback(), QSqlDriver::hasFeature(),
QString QSqlDatabase::userName ( ) const

Returns the connection's user name, the string may be empty.

See also
setUserName()