Home | All Classes | Main Classes | Annotated | Grouped Classes | Functions

TQSqlDatabase Class Reference
[sql module]

The TQSqlDatabase class is used to create SQL database connections and to provide transaction handling. More...

#include <ntqsqldatabase.h>

Inherits TQObject.

List of all member functions.

Public Members

Static Public Members

Properties

Protected Members


Detailed Description

The TQSqlDatabase class is used to create SQL database connections and to provide transaction handling.

Note that transaction handling is not supported by every SQL database. You can find out whether transactions are supported using TQSqlDriver::hasFeature().

The TQSqlDatabase class provides an abstract interface for accessing many types of database backends. Database-specific drivers are used internally to actually access and manipulate data, (see TQSqlDriver). Result set objects provide the interface for executing and manipulating SQL queries (see TQSqlQuery).

See also Database Classes.


Member Function Documentation

TQSqlDatabase::TQSqlDatabase ( const TQString & type, const TQString & name, TQObject * parent = 0, const char * objname = 0 ) [protected]

Creates a TQSqlDatabase connection called name that uses the driver referred to by type, with the parent parent and the object name objname. If the type is not recognized, the database connection will have no functionality.

The currently available drivers are:

Driver Type Description
TQODBC3 ODBC Driver (includes Microsoft SQL Server)
TQOCI8 Oracle Call Interface Driver
TQPSQL7 PostgreSQL v6.x and v7.x Driver
TQTDS7 Sybase Adaptive Server
TQMYSQL3 MySQL Driver
TQDB2 IBM DB2, v7.1 and higher
TQSQLITE SQLite Driver
TQIBASE Borland Interbase Driver

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

See also registerSqlDriver().

TQSqlDatabase::TQSqlDatabase ( TQSqlDriver * driver, TQObject * parent = 0, const char * objname = 0 ) [protected]

This is an overloaded member function, provided for convenience. It behaves essentially like the above function.

Creates a database connection using the driver driver, with the parent parent and the object name objname.

Warning: The framework takes ownership of the driver pointer, so it should not be deleted.

TQSqlDatabase::~TQSqlDatabase ()

Destroys the object and frees any allocated resources.

TQSqlDatabase * TQSqlDatabase::addDatabase ( const TQString & type, const TQString & connectionName = defaultConnection ) [static]

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

The database connection is referred to by connectionName. The newly added database connection is returned. This pointer is owned by TQSqlDatabase and will be deleted on program exit or when removeDatabase() is called.

If connectionName is not specified, the newly added database connection becomes the default database connection for the application, and subsequent calls to database() (without a database name parameter) will return a pointer to it. If connectionName is given, use database(connectionName) to retrieve a pointer to the database connection.

Warning: If you add a database with the same name as an existing database, the new database will replace the old one. This will happen automatically if you call this function more than once without specifying connectionName.

See also database() and removeDatabase().

Examples: sql/overview/connect1/main.cpp, sql/overview/connection.cpp, and sql/sqltable/main.cpp.

TQSqlDatabase * TQSqlDatabase::addDatabase ( TQSqlDriver * driver, const TQString & connectionName = defaultConnection ) [static]

This is an overloaded member function, provided for convenience. It behaves essentially like the above function.

This function is useful if you need to set up the database connection and instantiate the driver yourself. If you do this, it is recommended that you include the driver code in your own application. For example, setting up a custom PostgreSQL connection and instantiating the TQPSQL7 driver can be done the following way:

    #include "qtdir/src/sql/drivers/psql/qsql_psql.cpp"
    
(We assume that qtdir is the directory where TQt is installed.) This will pull in the code that is needed to use the PostgreSQL client library and to instantiate a TQPSQLDriver object, assuming that you have the PostgreSQL headers somewhere in your include search path.

    PGconn* con = PQconnectdb( "host=server user=bart password=simpson dbname=springfield" );
    TQPSQLDriver* drv =  new TQPSQLDriver( con );
    TQSqlDatabase* db = TQSqlDatabase::addDatabase( drv ); // becomes the new default connection
    TQSqlQuery q;
    q.exec( "SELECT * FROM people" );
    ...
    

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

Remember that you must link your application against the database client library as well. The simplest way to do this is to add lines like those below to your .pro file:

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

You will need to have the client library in your linker's search path.

The method described above will work for all the drivers, the only difference is the arguments the driver constructors take. Below is an overview of the drivers and their constructor arguments.

Driver Class name Constructor arguments File to include
TQPSQL7 TQPSQLDriver PGconn* connection qsql_psql.cpp
TQMYSQL3 TQMYSQLDriver MYSQL* connection qsql_mysql.cpp
TQOCI8 TQOCIDriver OCIEnv* environment, OCIError* error, OCISvcCtx* serviceContext qsql_oci.cpp
TQODBC3 TQODBCDriver SQLHANDLE environment, SQLHANDLE connection qsql_odbc.cpp
TQDB2 TQDB2 SQLHANDLE environment, SQLHANDLE connection qsql_db2.cpp
TQTDS7 TQTDSDriver LOGINREC* loginRecord, DBPROCESS* dbProcess, const TQString& hostName qsql_tds.cpp
TQSQLITE TQSQLiteDriver sqlite* connection qsql_sqlite.cpp
TQIBASE TQIBaseDriver isc_db_handle connection qsql_ibase.cpp

Note: The host name (or service name) is needed when constructing the TQTDSDriver for creating new connections for internal queries. This is to prevent the simultaneous usage of several TQSqlQuery/TQSqlCursor objects from blocking each other.

Warning: The SQL framework takes ownership of the driver pointer, and it should not be deleted. The returned TQSqlDatabase object is owned by the framework and must not be deleted. If you want to explicitly remove the connection, use removeDatabase()

See also drivers().

void TQSqlDatabase::close ()

Closes the database connection, freeing any resources acquired.

See also removeDatabase().

bool TQSqlDatabase::commit ()

Commits a transaction to the database if the driver supports transactions. Returns TRUE if the operation succeeded; otherwise returns FALSE.

See also TQSqlDriver::hasFeature() and rollback().

TQString TQSqlDatabase::connectOptions () const

Returns the database connect options. See the "connectOptions" property for details.

bool TQSqlDatabase::contains ( const TQString & connectionName = defaultConnection ) [static]

Returns TRUE if the list of database connections contains connectionName; otherwise returns FALSE.

TQSqlDatabase * TQSqlDatabase::database ( const TQString & connectionName = 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, 0 is returned. The pointer returned is owned by TQSqlDatabase and should not be deleted.

Warning: There are restrictions on the use of database connections in threaded applications. Please see the Thread Support in TQt document for more information about threading and SQL databases.

Examples: sql/overview/basicbrowsing/main.cpp and sql/overview/create_connections/main.cpp.

TQString TQSqlDatabase::databaseName () const

Returns the name of the database. See the "databaseName" property for details.

TQSqlDriver * TQSqlDatabase::driver () const

Returns the database driver used to access the database connection.

TQString TQSqlDatabase::driverName () const

Returns the name of the driver used by the database connection.

TQStringList TQSqlDatabase::drivers () [static]

Returns a list of all the available database drivers.

Note that if you want to iterate over the list, you should iterate over a copy, e.g.

    TQStringList list = TQSqlDatabase::drivers();
    TQStringList::Iterator it = list.begin();
    while( it != list.end() ) {
        myProcessing( *it );
        ++it;
    }
    

TQSqlQuery TQSqlDatabase::exec ( const TQString & query = TQString::null ) const

Executes a SQL statement (e.g. an INSERT, UPDATE or DELETE statement) on the database, and returns a TQSqlQuery object. Use lastError() to retrieve error information. If query is TQString::null, an empty, invalid query is returned and lastError() is not affected.

See also TQSqlQuery and lastError().

TQString TQSqlDatabase::hostName () const

Returns the host name where the database resides. See the "hostName" property for details.

bool TQSqlDatabase::isDriverAvailable ( const TQString & name ) [static]

Returns TRUE if a driver called name is available; otherwise returns FALSE.

See also drivers().

bool TQSqlDatabase::isOpen () const

Returns TRUE if the database connection is currently open; otherwise returns FALSE.

bool TQSqlDatabase::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.

TQSqlError TQSqlDatabase::lastError () const

Returns information about the last error that occurred on the database. See TQSqlError for more information.

Examples: sql/overview/connection.cpp and sql/sqltable/main.cpp.

bool TQSqlDatabase::open ()

Opens the database connection using the current connection values. Returns TRUE on success; otherwise returns FALSE. Error information can be retrieved using the lastError() function.

See also lastError().

Examples: sql/overview/connect1/main.cpp, sql/overview/connection.cpp, and sql/sqltable/main.cpp.

bool TQSqlDatabase::open ( const TQString & user, const TQString & password )

This is an overloaded member function, provided for convenience. It behaves essentially like the above 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 a connection and is then discarded.

See also lastError().

TQString TQSqlDatabase::password () const

Returns the password used to connect to the database. See the "password" property for details.

int TQSqlDatabase::port () const

Returns the port used to connect to the database. See the "port" property for details.

TQSqlIndex TQSqlDatabase::primaryIndex ( const TQString & tablename ) const

Returns the primary index for table tablename. If no primary index exists an empty TQSqlIndex will be returned.

TQSqlRecord TQSqlDatabase::record ( const TQString & tablename ) const

Returns a TQSqlRecord 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.

See also recordInfo().

TQSqlRecord TQSqlDatabase::record ( const TQSqlQuery & query ) const

This is an overloaded member function, provided for convenience. It behaves essentially like the above function.

Returns a TQSqlRecord populated with the names of all the fields used in the SQL query. If the query is a "SELECT *" the order in which fields appear in the record is undefined.

See also recordInfo().

TQSqlRecordInfo TQSqlDatabase::recordInfo ( const TQString & tablename ) const

Returns a TQSqlRecordInfo populated with meta data about the table or view tablename. If no such table (or view) exists, an empty record is returned.

See also TQSqlRecordInfo, TQSqlFieldInfo, and record().

TQSqlRecordInfo TQSqlDatabase::recordInfo ( const TQSqlQuery & query ) const

This is an overloaded member function, provided for convenience. It behaves essentially like the above function.

Returns a TQSqlRecordInfo object with meta data for the TQSqlQuery query. Note that this overloaded function may return less information than the recordInfo() function which takes the name of a table as parameter.

See also TQSqlRecordInfo, TQSqlFieldInfo, and record().

void TQSqlDatabase::registerSqlDriver ( const TQString & name, const TQSqlDriverCreatorBase * 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 usage:

    TQSqlDatabase::registerSqlDriver( "MYDRIVER", new TQSqlDriverCreator<MyDatabaseDriver> );
    TQSqlDatabase* db = TQSqlDatabase::addDatabase( "MYDRIVER" );
    ...
    

Warning: The framework takes ownership of the creator pointer, so it should not be deleted.

void TQSqlDatabase::removeDatabase ( const TQString & 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.

void TQSqlDatabase::removeDatabase ( TQSqlDatabase * db ) [static]

This is an overloaded member function, provided for convenience. It behaves essentially like the above function.

Removes the database connection db from the list of database connections. The TQSqlDatabase object is destroyed when it is removed from the list.

Warning: The db pointer is not valid after this function has been called. There should be no open queries on the database connection when this function is called, otherwise a resource leak will occur.

bool TQSqlDatabase::rollback ()

Rolls a transaction back on the database if the driver supports transactions. Returns TRUE if the operation succeeded; otherwise returns FALSE.

See also TQSqlDriver::hasFeature(), commit(), and transaction().

void TQSqlDatabase::setConnectOptions ( const TQString & options = TQString::null )

Sets the database connect options to options. See the "connectOptions" property for details.

void TQSqlDatabase::setDatabaseName ( const TQString & name ) [virtual]

Sets the name of the database to name. See the "databaseName" property for details.

void TQSqlDatabase::setHostName ( const TQString & host ) [virtual]

Sets the host name where the database resides to host. See the "hostName" property for details.

void TQSqlDatabase::setPassword ( const TQString & password ) [virtual]

Sets the password used to connect to the database to password. See the "password" property for details.

void TQSqlDatabase::setPort ( int p ) [virtual]

Sets the port used to connect to the database to p. See the "port" property for details.

void TQSqlDatabase::setUserName ( const TQString & name ) [virtual]

Sets the user name connected to the database to name. See the "userName" property for details.

TQStringList TQSqlDatabase::tables ( TQSql::TableType type ) const

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

Note that if you want to iterate over the list, you should iterate over a copy, e.g.

    TQStringList list = myDatabase.tables( TQSql::Tables | TQSql::Views );
    TQStringList::Iterator it = list.begin();
    while( it != list.end() ) {
        myProcessing( *it );
        ++it;
    }
    

Example: sql/sqltable/main.cpp.

TQStringList TQSqlDatabase::tables () const

This is an overloaded member function, provided for convenience. It behaves essentially like the above function.

Returns a list of the database's tables that are visible to the user. To include views or system tables, use the version of this function that takes a table type parameter.

Note that if you want to iterate over the list, you should iterate over a copy, e.g.

    TQStringList list = myDatabase.tables();
    TQStringList::Iterator it = list.begin();
    while( it != list.end() ) {
        myProcessing( *it );
        ++it;
    }
    

bool TQSqlDatabase::transaction ()

Begins a transaction on the database if the driver supports transactions. Returns TRUE if the operation succeeded; otherwise returns FALSE.

See also TQSqlDriver::hasFeature(), commit(), and rollback().

TQString TQSqlDatabase::userName () const

Returns the user name connected to the database. See the "userName" property for details.


Property Documentation

TQString connectOptions

This property holds the database connect options.

The format of the options string is a semi-colon 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

  • CLIENT_COMPRESS
  • CLIENT_FOUND_ROWS
  • CLIENT_IGNORE_SPACE
  • CLIENT_SSL
  • CLIENT_ODBC
  • CLIENT_NO_SCHEMA
  • CLIENT_INTERACTIVE

  • connect_timeout
  • options
  • tty
  • requiressl
  • service
DB2 OCI TDS
  • SQL_ATTR_ACCESS_MODE
  • SQL_ATTR_LOGIN_TIMEOUT

none

none

Example of usage:

    ...
    // MySQL connection
    db->setConnectOptions( "CLIENT_SSL;CLIENT_IGNORE_SPACE" ); // 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
        ...
    }
    

Please refer to the client library documentation for more information about the different options. The options will be set prior to opening the database connection. Setting new options without re-opening the connection does nothing.

See also

Set this property's value with setConnectOptions() and get this property's value with connectOptions().

TQString databaseName

This property holds the name of the database.

Note that the database name is the TNS Service Name for the TQOCI8 (Oracle) driver.

For the TQODBC3 driver it can either be a DSN, a DSN filename (the file must have a .dsn extension), or a connection string. MS Access users can for example use the following connection string to open a .mdb file directly, instead of having to create a DSN entry in the ODBC manager:

    ...
    db = TQSqlDatabase::addDatabase( "TQODBC3" );
    db->setDatabaseName( "DRIVER={Microsoft Access Driver (*.mdb)};FIL={MS Access};DBQ=myaccessfile.mdb" );
    if ( db->open() ) {
        // success!
    }
    ...
    
("FIL" is the required spelling in Microsoft's API.)

There is no default value.

Set this property's value with setDatabaseName() and get this property's value with databaseName().

TQString hostName

This property holds the host name where the database resides.

There is no default value.

Set this property's value with setHostName() and get this property's value with hostName().

TQString password

This property holds the password used to connect to the database.

There is no default value.

Warning: This function stores the password in plain text within TQt. Use the open() call that takes a password as parameter to avoid this behaviour.

See also open().

Set this property's value with setPassword() and get this property's value with password().

int port

This property holds the port used to connect to the database.

There is no default value.

Set this property's value with setPort() and get this property's value with port().

TQString userName

This property holds the user name connected to the database.

There is no default value.

Set this property's value with setUserName() and get this property's value with userName().


This file is part of the TQt toolkit. Copyright © 1995-2007 Trolltech. All Rights Reserved.


Copyright © 2007 TrolltechTrademarks
TQt 3.3.8