## wxDb

A wxDb instance is a connection to an ODBC data source which may be opened, closed, and re-opened an unlimited number of times. A database connection allows function to be performed directly on the data source, as well as allowing access to any tables/views defined in the data source to which the user has sufficient privileges.

Include files

<wx/db.h>

Helper classes and data structures

The following classes and structs are defined in db.cpp/.h for use with the wxDb class.

- wxDbColFor
- wxDbColInf
- wxDbTableInf
- wxDbInf

Constants

NOTE: In a future release, all ODBC class constants will be prefaced with 'wx'

        wxDB_PATH_MAX           Maximum path length allowed to be passed to the ODBC
                                driver to indicate where the data file is located.

        DB_MAX_COLUMN_NAME_LEN  Maximum supported length for the name of a column

        DB_MAX_ERROR_HISTORY    Maximum number of error messages retained in the
                                queue before being overwritten by new errors.

        DB_MAX_ERROR_MSG_LEN    Maximum supported length of an error message returned
                                by the ODBC classes

        DB_MAX_STATEMENT_LEN    Maximum supported length for a complete SQL statement
                                to be passed to the ODBC driver

        DB_MAX_TABLE_NAME_LEN   Maximum supported length for the name of a table

        DB_MAX_WHERE_CLAUSE_LEN Maximum supported WHERE clause length that can be
                                passed to the ODBC driver

        DB_TYPE_NAME_LEN        Maximum length of the name of a column's data type

Enumerated types

enum wxDbSqlLogState

sqlLogOFF, sqlLogON

enum wxDBMS

These are the databases currently tested and working with the ODBC classes. A call to wxDb::Dbms will return one of these enumerated values listed below.

          dbmsUNIDENTIFIED,
          dbmsORACLE,
          dbmsSYBASE_ASA,     // Adaptive Server Anywhere
          dbmsSYBASE_ASE,     // Adaptive Server Enterprise
          dbmsMS_SQL_SERVER,
          dbmsMY_SQL,
          dbmsPOSTGRES,
          dbmsACCESS,
          dbmsDBASE,
          dbmsINFORMIX

See the remarks in wxDb::Dbms for exceptions/issues with each of these database engines.

Public member variables

SWORD wxDb::cbErrorMsg

This member variable is populated as a result of calling wxDb::GetNextError. Contains the count of bytes in the wxDb::errorMsg string.

int wxDb::DB_STATUS

The last ODBC error that occurred on this data connection. Possible codes are:

       DB_ERR_GENERAL_WARNING                     // SqlState = '01000'
       DB_ERR_DISCONNECT_ERROR                    // SqlState = '01002'
       DB_ERR_DATA_TRUNCATED                      // SqlState = '01004'
       DB_ERR_PRIV_NOT_REVOKED                    // SqlState = '01006'
       DB_ERR_INVALID_CONN_STR_ATTR               // SqlState = '01S00'
       DB_ERR_ERROR_IN_ROW                        // SqlState = '01S01'
       DB_ERR_OPTION_VALUE_CHANGED                // SqlState = '01S02'
       DB_ERR_NO_ROWS_UPD_OR_DEL                  // SqlState = '01S03'
       DB_ERR_MULTI_ROWS_UPD_OR_DEL               // SqlState = '01S04'
       DB_ERR_WRONG_NO_OF_PARAMS                  // SqlState = '07001'
       DB_ERR_DATA_TYPE_ATTR_VIOL                 // SqlState = '07006'
       DB_ERR_UNABLE_TO_CONNECT                   // SqlState = '08001'
       DB_ERR_CONNECTION_IN_USE                   // SqlState = '08002'
       DB_ERR_CONNECTION_NOT_OPEN                 // SqlState = '08003'
       DB_ERR_REJECTED_CONNECTION                 // SqlState = '08004'
       DB_ERR_CONN_FAIL_IN_TRANS                  // SqlState = '08007'
       DB_ERR_COMM_LINK_FAILURE                   // SqlState = '08S01'
       DB_ERR_INSERT_VALUE_LIST_MISMATCH          // SqlState = '21S01'
       DB_ERR_DERIVED_TABLE_MISMATCH              // SqlState = '21S02'
       DB_ERR_STRING_RIGHT_TRUNC                  // SqlState = '22001'
       DB_ERR_NUMERIC_VALUE_OUT_OF_RNG            // SqlState = '22003'
       DB_ERR_ERROR_IN_ASSIGNMENT                 // SqlState = '22005'
       DB_ERR_DATETIME_FLD_OVERFLOW               // SqlState = '22008'
       DB_ERR_DIVIDE_BY_ZERO                      // SqlState = '22012'
       DB_ERR_STR_DATA_LENGTH_MISMATCH            // SqlState = '22026'
       DB_ERR_INTEGRITY_CONSTRAINT_VIOL           // SqlState = '23000'
       DB_ERR_INVALID_CURSOR_STATE                // SqlState = '24000'
       DB_ERR_INVALID_TRANS_STATE                 // SqlState = '25000'
       DB_ERR_INVALID_AUTH_SPEC                   // SqlState = '28000'
       DB_ERR_INVALID_CURSOR_NAME                 // SqlState = '34000'
       DB_ERR_SYNTAX_ERROR_OR_ACCESS_VIOL         // SqlState = '37000'
       DB_ERR_DUPLICATE_CURSOR_NAME               // SqlState = '3C000'
       DB_ERR_SERIALIZATION_FAILURE               // SqlState = '40001'
       DB_ERR_SYNTAX_ERROR_OR_ACCESS_VIOL2        // SqlState = '42000'
       DB_ERR_OPERATION_ABORTED                   // SqlState = '70100'
       DB_ERR_UNSUPPORTED_FUNCTION                // SqlState = 'IM001'
       DB_ERR_NO_DATA_SOURCE                      // SqlState = 'IM002'
       DB_ERR_DRIVER_LOAD_ERROR                   // SqlState = 'IM003'
       DB_ERR_SQLALLOCENV_FAILED                  // SqlState = 'IM004'
       DB_ERR_SQLALLOCCONNECT_FAILED              // SqlState = 'IM005'
       DB_ERR_SQLSETCONNECTOPTION_FAILED          // SqlState = 'IM006'
       DB_ERR_NO_DATA_SOURCE_DLG_PROHIB           // SqlState = 'IM007'
       DB_ERR_DIALOG_FAILED                       // SqlState = 'IM008'
       DB_ERR_UNABLE_TO_LOAD_TRANSLATION_DLL      // SqlState = 'IM009'
       DB_ERR_DATA_SOURCE_NAME_TOO_LONG           // SqlState = 'IM010'
       DB_ERR_DRIVER_NAME_TOO_LONG                // SqlState = 'IM011'
       DB_ERR_DRIVER_KEYWORD_SYNTAX_ERROR         // SqlState = 'IM012'
       DB_ERR_TRACE_FILE_ERROR                    // SqlState = 'IM013'
       DB_ERR_TABLE_OR_VIEW_ALREADY_EXISTS        // SqlState = 'S0001'
       DB_ERR_TABLE_NOT_FOUND                     // SqlState = 'S0002'
       DB_ERR_INDEX_ALREADY_EXISTS                // SqlState = 'S0011'
       DB_ERR_INDEX_NOT_FOUND                     // SqlState = 'S0012'
       DB_ERR_COLUMN_ALREADY_EXISTS               // SqlState = 'S0021'
       DB_ERR_COLUMN_NOT_FOUND                    // SqlState = 'S0022'
       DB_ERR_NO_DEFAULT_FOR_COLUMN               // SqlState = 'S0023'
       DB_ERR_GENERAL_ERROR                       // SqlState = 'S1000'
       DB_ERR_MEMORY_ALLOCATION_FAILURE           // SqlState = 'S1001'
       DB_ERR_INVALID_COLUMN_NUMBER               // SqlState = 'S1002'
       DB_ERR_PROGRAM_TYPE_OUT_OF_RANGE           // SqlState = 'S1003'
       DB_ERR_SQL_DATA_TYPE_OUT_OF_RANGE          // SqlState = 'S1004'
       DB_ERR_OPERATION_CANCELLED                 // SqlState = 'S1008'
       DB_ERR_INVALID_ARGUMENT_VALUE              // SqlState = 'S1009'
       DB_ERR_FUNCTION_SEQUENCE_ERROR             // SqlState = 'S1010'
       DB_ERR_OPERATION_INVALID_AT_THIS_TIME      // SqlState = 'S1011'
       DB_ERR_INVALID_TRANS_OPERATION_CODE        // SqlState = 'S1012'
       DB_ERR_NO_CURSOR_NAME_AVAIL                // SqlState = 'S1015'
       DB_ERR_INVALID_STR_OR_BUF_LEN              // SqlState = 'S1090'
       DB_ERR_DESCRIPTOR_TYPE_OUT_OF_RANGE        // SqlState = 'S1091'
       DB_ERR_OPTION_TYPE_OUT_OF_RANGE            // SqlState = 'S1092'
       DB_ERR_INVALID_PARAM_NO                    // SqlState = 'S1093'
       DB_ERR_INVALID_SCALE_VALUE                 // SqlState = 'S1094'
       DB_ERR_FUNCTION_TYPE_OUT_OF_RANGE          // SqlState = 'S1095'
       DB_ERR_INF_TYPE_OUT_OF_RANGE               // SqlState = 'S1096'
       DB_ERR_COLUMN_TYPE_OUT_OF_RANGE            // SqlState = 'S1097'
       DB_ERR_SCOPE_TYPE_OUT_OF_RANGE             // SqlState = 'S1098'
       DB_ERR_NULLABLE_TYPE_OUT_OF_RANGE          // SqlState = 'S1099'
       DB_ERR_UNIQUENESS_OPTION_TYPE_OUT_OF_RANGE // SqlState = 'S1100'
       DB_ERR_ACCURACY_OPTION_TYPE_OUT_OF_RANGE   // SqlState = 'S1101'
       DB_ERR_DIRECTION_OPTION_OUT_OF_RANGE       // SqlState = 'S1103'
       DB_ERR_INVALID_PRECISION_VALUE             // SqlState = 'S1104'
       DB_ERR_INVALID_PARAM_TYPE                  // SqlState = 'S1105'
       DB_ERR_FETCH_TYPE_OUT_OF_RANGE             // SqlState = 'S1106'
       DB_ERR_ROW_VALUE_OUT_OF_RANGE              // SqlState = 'S1107'
       DB_ERR_CONCURRENCY_OPTION_OUT_OF_RANGE     // SqlState = 'S1108'
       DB_ERR_INVALID_CURSOR_POSITION             // SqlState = 'S1109'
       DB_ERR_INVALID_DRIVER_COMPLETION           // SqlState = 'S1110'
       DB_ERR_INVALID_BOOKMARK_VALUE              // SqlState = 'S1111'
       DB_ERR_DRIVER_NOT_CAPABLE                  // SqlState = 'S1C00'
       DB_ERR_TIMEOUT_EXPIRED                     // SqlState = 'S1T00'

struct wxDb::dbInf

This structure is internal to the wxDb class and contains details of the ODBC datasource that the current instance of the wxDb is connected to in its members. When the data source is opened, all of the information contained in the dbInf structure is queried from the data source. This information is used almost exclusively within the ODBC class library. Where there is a need for this information outside of the class library a member function such as wxDbTable::IsCursorClosedOnCommit() has been added for ease of use.

       char   dbmsName[40]        - Name of the dbms product
       char   dbmsVer[64]         - Version # of the dbms product
       char   driverName[40]      - Driver name
       char   odbcVer[60]         - ODBC version of the driver
       char   drvMgrOdbcVer[60]   - ODBC version of the driver manager
       char   driverVer[60]       - Driver version
       char   serverName[80]      - Server Name, typically a connect string
       char   databaseName[128]   - Database filename
       char   outerJoins[2]       - Does datasource support outer joins
       char   procedureSupport[2] - Does datasource support stored procedures
       UWORD  maxConnections      - Maximum # of connections datasource supports
       UWORD  maxStmts            - Maximum # of HSTMTs per HDBC
       UWORD  apiConfLvl          - ODBC API conformance level
       UWORD  cliConfLvl          - Is datasource SAG compliant
       UWORD  sqlConfLvl          - SQL conformance level
       UWORD  cursorCommitBehavior   - How cursors are affected on db commit
       UWORD  cursorRollbackBehavior - How cursors are affected on db rollback
       UWORD  supportNotNullClause   - Does datasource support NOT NULL clause
       char   supportIEF[2]       - Integrity Enhancement Facility (Ref. Integrity)
       UDWORD txnIsolation        - Transaction isolation level supported by driver
       UDWORD txnIsolationOptions - Transaction isolation level options available
       UDWORD fetchDirections     - Fetch directions supported
       UDWORD lockTypes           - Lock types supported in SQLSetPos
       UDWORD posOperations       - Position operations supported in SQLSetPos
       UDWORD posStmts            - Position statements supported
       UDWORD scrollConcurrency   - Scrollable cursor concurrency options supported
       UDWORD scrollOptions       - Scrollable cursor options supported
       UDWORD staticSensitivity   - Can additions/deletions/updates be detected
       UWORD  txnCapable          - Indicates if datasource supports transactions
       UDWORD loginTimeout        - Number seconds to wait for a login request

char wxDb::errorList[DB_MAX_ERROR_HISTORY][DB_MAX_ERROR_MSG_LEN]

The last n ODBC errors that have occurred on this database connection.

char wxDb::errorMsg[SQL_MAX_MESSAGE_LENGTH]

This member variable is populated as a result of calling wxDb::GetNextError. It contains the ODBC error message text.

SDWORD wxDb::nativeError

Set by wxDb::DispAllErrors, wxDb::GetNextError, and wxDb::DispNextError. It contains the datasource-specific error code returned by the datasource to the ODBC driver. Used for reporting ODBC errors.

wxChar wxDb::sqlState[20]

Set by wxDb::TranslateSqlState(). Indicates the error state after a failed ODBC operation. Used for reporting ODBC errors.

Remarks

Default cursor scrolling is defined by wxODBC_FWD_ONLY_CURSORS in setup.h when the wxWindows library is built. This behavior can be overridden when an instance of a wxDb is created (see wxDb constructor).

See also

wxDbColFor, wxDbColInf, wxDbTable, wxDbTableInf, wxDbInf

Associated non-class functions
wxDb::wxDb
wxDb::Catalog
wxDb::Close
wxDb::CommitTrans
wxDb::CreateView
wxDb::DispAllErrors
wxDb::DispNextError
wxDb::DropView
wxDb::ExecSql
wxDb::FwdOnlyCursors
wxDb::GetCatalog
wxDb::GetColumnCount
wxDb::GetColumns
wxDb::GetData
wxDb::GetDatabaseName
wxDb::GetDataSource
wxDb::GetHDBC
wxDb::GetHENV
wxDb::GetHSTMT
wxDb::GetKeyFields
wxDb::GetNext
wxDb::GetNextError
wxDb::GetPassword
wxDb::GetTableCount
wxDb::GetUsername
wxDb::Grant
wxDb::IsFwdOnlyCursors
wxDb::IsOpen
wxDb::Open
wxDb::RollbackTrans
wxDb::SetSqlLogging
wxDb::TableExists
wxDb::TranslateSqlState
wxDb::WriteSqlLog
wxDb::Dbms
wxDb::SetDebugErrorMessages
wxDb::LogError

### Associated non-class functions

The following functions are used in conjunction with the wxDb class.

wxDb * wxDbGetConnection(wxDbConnectInf *pDbConfig, bool FwdOnlyCursors=(bool)wxODBC_FWD_ONLY_CURSORS)

bool wxDbFreeConnection(wxDb *pDb)

void wxDbCloseConnections()

int wxDbConnectionsInUse()

bool wxDbSqlLog(wxDbSqlLogState state, const wxChar *filename = SQL_LOG_FILENAME)

bool wxDbGetDataSource(HENV henv, char *Dsn, SWORD DsnMax, char *DsDesc, SWORD DsDescMax, UWORD direction = SQL_FETCH_NEXT)

Members

### wxDb::wxDb

wxDb()

Default constructor.

wxDb(HENV& aHenv, bool FwdOnlyCursors=(bool)wxODBC_FWD_ONLY_CURSORS)

Constructor, used to create an ODBC connection to a data source.

Parameters

aHenv

Environment handle used for this connection.

FwdOnlyCursors

Will cursors created for use with this datasource connection only allow forward scrolling cursors.

Remarks

This is the constructor for the wxDb class. The wxDb object must be created and opened before any database activity can occur.

Example

       wxDbConnectInf ConnectInf;
       ....Set values for member variables of ConnectInf here

       wxDb sampleDB(ConnectInf.Henv);
       if (!sampleDB.Open(ConnectInf.Dsn, ConnectInf.Uid, ConnectInf.AuthStr))
       {
          // Error opening data source
       }

### wxDb::Catalog

bool Catalog(char * userID, char *fileName = SQL_CATALOG_FILENAME)

Allows a data "dictionary" of the data source to be created, dumping pertinent information about all data tables to which the user specified in userID has access.

Parameters

userID

Database user name to use in accessing the database. All tables to which this user has rights will be evaluated in the catalog.

fileName

OPTIONAL argument. Name of the text file to create and write the DB catalog to.

Return value

Returns TRUE if the catalog request was successful, of FALSE if there was some reason the catalog could not be generated

Example

    ============== ============== ================ ========= =======
    TABLE NAME     COLUMN NAME    DATA TYPE        PRECISION  LENGTH
    ============== ============== ================ ========= =======
    EMPLOYEE       RECID          (0008)NUMBER            15       8
    EMPLOYEE       USER_ID        (0012)VARCHAR2          13      13
    EMPLOYEE       FULL_NAME      (0012)VARCHAR2          26      26
    EMPLOYEE       PASSWORD       (0012)VARCHAR2          26      26
    EMPLOYEE       START_DATE     (0011)DATE              19      16

### wxDb::Close

void Close()

Closes the database connection.

Remarks

At the end of your program, when you have finished all of your database work, you must close the ODBC connection to the data source. There are actually four steps involved in doing this as illustrated in the example.

Any wxDbTable instances which use this connection must be deleted before closing the database connection.

Example

       // Commit any open transactions on the data source
       sampleDB.CommitTrans();

       // Delete any remaining wxDbTable objects allocated with new
       delete parts;

       // Close the wxDb connection when finished with it
       sampleDB.Close();

       // Free Environment Handle that ODBC uses
       if (SQLFreeEnv(Db.Henv) != SQL_SUCCESS)
       {
          // Error freeing environment handle
       }

### wxDb::CommitTrans

bool CommitTrans()

Permanently "commits" changes (insertions/deletions/updates) to the database.

Return value

Returns TRUE if the commit was successful, or FALSE if the commit failed.

Remarks

Transactions begin implicitly as soon as you make a change to the database. At any time thereafter, you can save your work to the database ("Commit") or roll back all of your changes ("Rollback"). Calling this member function commits all open transactions on this ODBC connection.

Special Note : Cursors

It is important to understand that different database/ODBC driver combinations handle transactions differently. One thing in particular that you must pay attention to is cursors, in regard to transactions. Cursors are what allow you to scroll through records forward and backward and to manipulate records as you scroll through them. When you issue a query, a cursor is created behind the scenes. The cursor keeps track of the query and keeps track of the current record pointer. After you commit or rollback a transaction, the cursor may be closed automatically. This means you must requery the data source before you can perform any additional work against the wxDbTable object. This is only necessary however if the data source closes the cursor after a commit or rollback. Use the wxDbTable::IsCursorClosedOnCommit() member function to determine the data source's transaction behavior. Note, it would be very inefficient to just assume the data source closes the cursor and always requery. This could put a significant, unnecessary load on data sources that leave the cursors open after a transaction.

### wxDb::CreateView

bool CreateView(char * viewName, char * colList, char *pSqlStmt)

Creates a SQL VIEW.

Parameters

viewName

The name of the view. e.g. PARTS_V

colList

OPTIONAL Pass in a comma delimited list of column names if you wish to explicitly name each column in the result set. If not desired, pass in an empty string.

pSqlStmt

Pointer to the select statement portion of the CREATE VIEW statement. Must be a complete, valid SQL SELECT statement.

Remarks

A 'view' is a logical table that derives columns from one or more other tables or views. Once the view is created, it can be queried exactly like any other table in the database.

NOTE: Views are not available with all datasources. Oracle is one example of a datasouce which does support views.

Example

       // Incomplete code sample
       db.CreateView("PARTS_SD1", "PN, PD, QTY",
                     "SELECT PART_NO, PART_DESC, QTY_ON_HAND * 1.1 FROM PARTS \
                      WHERE STORAGE_DEVICE = 1");

       // PARTS_SD1 can now be queried just as if it were a data table.
       // e.g. SELECT PN, PD, QTY FROM PARTS_SD1

### wxDb::DispAllErrors

bool DispAllErrors(HENV aHenv, HDBC aHdbc = SQL_NULL_HDBC, HSTMT aHstmt = SQL_NULL_HSTMT)

Logs all database errors that occurred as a result of the last executed database command. This logging also includes debug logging when compiled in debug mode via wxLogDebug. If logging is turned on via wxDb::SetSqlLogging, then an entry is also logged to the defined log file.

Parameters

aHenv

A handle to the ODBC environment.

aHdbc

A handle to the ODBC connection. Pass this in if the ODBC function call that erred out required a hdbc or hstmt argument.

AHstmt

A handle to the ODBC statement being executed against. Pass this in if the ODBC function call that erred out required a hstmt argument.

Remarks

This member function will display all of the ODBC error messages for the last ODBC function call that was made. Normally used internally within the ODBC class library. Would be used externally if calling ODBC functions directly (i.e. SQLFreeEnv()).

See also

wxDb::SetSqlLogging, wxDbSqlLog

Example

       if (SQLExecDirect(hstmt, (UCHAR FAR *) pSqlStmt, SQL_NTS) != SQL_SUCCESS)
          // Display all ODBC errors for this stmt
          return(db.DispAllErrors(db.henv, db.hdbc, hstmt));

### wxDb::DispNextError

void DispNextError()

Remarks

This function is normally used internally within the ODBC class library. It could be used externally if calling ODBC functions directly. This function works in conjunction with wxDb::GetNextError when errors (or sometimes informational messages) returned from ODBC need to be analyzed rather than simply displaying them as an error. GetNextError() retrieves the next ODBC error from the ODBC error queue. The wxDb member variables "sqlState", "nativeError" and "errorMsg" could then be evaluated. To display the error retrieved, DispNextError() could then be called. The combination of GetNextError() and DispNextError() can be used to iteratively step through the errors returned from ODBC evaluating each one in context and displaying the ones you choose.

Example

       // Drop the table before attempting to create it
       sprintf(sqlStmt, "DROP TABLE %s", tableName);
       // Execute the drop table statement
       if (SQLExecDirect(hstmt,(UCHAR FAR *)sqlStmt,SQL_NTS) != SQL_SUCCESS)
       {
          // Check for sqlState = S0002, "Table or view not found".
          // Ignore this error, bomb out on any other error.
          pDb->GetNextError(henv, hdbc, hstmt);
          if (strcmp(pDb->sqlState, "S0002"))
          {
             pDb->DispNextError();   // Displayed error retrieved
             pDb->DispAllErrors(henv, hdbc, hstmt); // Display all other errors, if any
             pDb->RollbackTrans();   // Rollback the transaction
             CloseCursor();          // Close the cursor
             return(FALSE);          // Return Failure
          }
       }

### wxDb::DropView

bool DropView(const char *viewName)

Drops the data table view named in 'viewName'.

Parameters

viewName

Name of the view to be dropped.

Remarks

If the view does not exist, this function will return TRUE. Note that views are not supported with all data sources.

### wxDb::ExecSql

bool ExecSql(char *pSqlStmt)

Allows a native SQL command to be executed directly against the datasource. In addition to being able to run any standard SQL command, use of this function allows a user to (potentially) utilize features specific to the datasource they are connected to that may not be available through ODBC. The ODBC driver will pass the specified command directly to the datasource.

Parameters

pSqlStmt

Pointer to the SQL statement to be executed.

Remarks

This member extends the wxDb class and allows you to build and execute ANY VALID SQL statement against the data source. This allows you to extend the class library by being able to issue any SQL statement that the data source is capable of processing.

See also

wxDb::GetData, wxDb::GetNext

### wxDb::FwdOnlyCursors

bool FwdOnlyCursors()

Indicates whether this connection to the datasource only allows forward scrolling cursors or not. This state is set at connection creation time.

Remarks

In wxWindows v2.4 release, this function will be deprecated to use a renamed version of the function called wxDb::IsFwdOnlyCursors() to match the normal wxWindows naming conventions for class member functions.

See also

wxDb::IsFwdOnlyCursors, wxDb::wxDb, wxDbGetConnection

### wxDb::GetCatalog

wxDbInf * GetCatalog(char *userID)

Returns a wxDbInf pointer that points to the catalog(data source) name, schema, number of tables accessible to the current user, and a wxDbTableInf pointer to all data pertaining to all tables in the users catalog.

Parameters

userID

Owner of the table. Specify a userID when the datasource you are connected to allows multiple unique tables with the same name to be owned by different users. userID is evaluated as follows:

             userID == NULL  ... UserID is ignored (DEFAULT)
             userID == ""    ... UserID set equal to 'this->uid'
             userID != ""    ... UserID set equal to 'userID'

Remarks

The returned catalog will only contain catalog entries for tables to which the user specified in 'userID' has sufficient privileges. If no user is specified (NULL passed in), a catalog pertaining to all tables in the datasource accessible via this connection will be returned.

### wxDb::GetColumnCount

int GetColumnCount(char *tableName, const char *userID)

Parameters

tableName

A table name you wish to obtain column information about.

userID

Name of the user that owns the table(s). Required for some datasources for situations where there may be multiple tables with the same name in the datasource, but owned by different users. userID is evaluated in the following manner:

             userID == NULL  ... UserID is ignored (DEFAULT)
             userID == ""    ... UserID set equal to 'this->uid'
             userID != ""    ... UserID set equal to 'userID'

Return value

Returns a count of how many columns are in the specified table. If an error occurs retrieving the number of columns the function will return a -1.

### wxDb::GetColumns

wxDbColInf * GetColumns(char *tableName, int *numCols, const char *userID=NULL)

wxDbColInf * GetColumns(char *tableName[], const char *userID)

Parameters

tableName

A table name you wish to obtain column information about.

numCols

A pointer to a integer which will hold a count of the number of columns returned by this function

tableName[]

An array of pointers to table names you wish to obtain column information about. The last element of this array must be a NULL string.

userID

Name of the user that owns the table(s). Required for some datasources for situations where there may be multiple tables with the same name in the datasource, but owned by different users. userID is evaluated in the following manner:

             userID == NULL  ... UserID is ignored (DEFAULT)
             userID == ""    ... UserID set equal to 'this->uid'
             userID != ""    ... UserID set equal to 'userID'

Return value

This function returns an array of wxDbColInf structures. This allows you to obtain information regarding the columns of your table(s). If no columns were found, or an error occurred, this pointer will be zero (null).

THE CALLING FUNCTION IS RESPONSIBLE FOR DELETING THE wxDbColInf MEMORY WHEN IT IS FINISHED WITH IT.

ALL column bindings associated with this wxDb instance are unbound by this function. This function should use its own wxDb instance to avoid undesired unbinding of columns.

See also

wxDbColInf

Example

       char *tableList[] = {"PARTS", 0};
       wxDbColInf *colInf = pDb->GetColumns(tableList);
       if (colInf)
       {
          // Use the column inf
          .......
          // Destroy the memory
          delete [] colInf;
       }

### wxDb::GetData

bool GetData(UWORD colNo, SWORD cType, PTR pData, SDWORD maxLen, SDWORD FAR * cbReturned )

Used to retrieve result set data without binding column values to memory variables (i.e. not using a wxDbTable instance to access table data).

Parameters

colNo

Ordinal number of column in the result set to be returned.

cType

The C data type that is to be returned.

pData

Memory buffer which will hold the data returned by the call to this function.

maxLen

Maximum size of the buffer that will hold the returned value.

cbReturned

Pointer to the buffer containing the length of the actual data returned. If this value comes back as SQL_NULL_DATA, then the GetData() call has failed.

See also

wxDb::GetNext, wxDb::ExecSql

Example

    	SDWORD cb;
    	ULONG reqQty;
    	wxString sqlStmt;
    	sqlStmt = "SELECT SUM(REQUIRED_QTY - PICKED_QTY) FROM ORDER_TABLE WHERE \
                     PART_RECID = 1450 AND REQUIRED_QTY > PICKED_QTY";

    	// Perform the query
    	if (!pDb->ExecSql(sqlStmt.c_str()))
    	{
    		// ERROR
    		return(0);
    	}

    	// Request the first row of the result set
    	if (!pDb->GetNext())
    	{
    		// ERROR
    		return(0);
    	}

    	Read column #1 of this row of the result set and store the value in 'reqQty'
    	if (!pDb->GetData(1, SQL_C_ULONG, &reqQty, 0, &cb))
    	{
    		// ERROR
    		return(0);
    	}

    	// Check for a NULL result
    	if (cb == SQL_NULL_DATA)
    		return(0);

Remarks

When requesting multiple columns to be returned from the result set (for example, the SQL query requested 3 columns be returned), the calls to GetData must request the columns in ordinal sequence (1,2,3 or 1,3 or 2,3).

### wxDb::GetDatabaseName

char * GetDatabaseName()

Returns the name of the database engine.

### wxDb::GetDataSource

char * GetDataSource()

Returns the ODBC datasource name.

### wxDb::GetHDBC

HDBC GetHDBC()

Returns the ODBC handle to the database connection.

### wxDb::GetHENV

HENV GetHENV()

Returns the ODBC environment handle.

### wxDb::GetHSTMT

HSTMT GetHSTMT()

Returns the ODBC statement handle associated with this database connection.

### wxDb::GetKeyFields

int GetKeyFields(char *tableName, wxDbColInf *colInf, intnocols)

Used to determine which columns are members of primary or non-primary indexes on the specified table. If a column is a member of a foreign key for some other table, that information is detected also.

This function is primarily for use by the wxDb::GetColumns function, but may be called if desired from the client application.

Parameters

tableName

Name of the table for which the columns will be evaluated as to their inclusion in any indexes.

colInf

Data structure containing the column definitions (obtained with wxDb::GetColumns). This function populates the PkCol, PkTableName, and FkTableName members of the colInf structure.

nocols

Number of columns defined in the instance of colInf.

Return value

Currently always returns TRUE.

See also

wxDbColInf, wxDb::GetColumns

### wxDb::GetNext

bool GetNext()

Requests the next row in the result set obtained by issueing a query through a direct request using wxDb::ExecSql().

See also

wxDb::ExecSql, wxDb::GetData

### wxDb::GetNextError

bool GetNextError(HENV aHenv, HDBC aHdbc = SQL_NULL_HDBC, HSTMT aHstmt = SQL_NULL_HSTMT)

Parameters

aHenv

A handle to the ODBC environment.

aHdbc

A handle to the ODBC connection. Pass this in if the ODBC function call that erred out required a hdbc or hstmt argument.

AHstmt

A handle to the ODBC statement being executed against. Pass this in if the ODBC function call that erred out requires a hstmt argument.

See also

wxDb::DispNextError, wxDb::DispAllErrors

Example

       if (SQLExecDirect(hstmt, (UCHAR FAR *) pSqlStmt, SQL_NTS) != SQL_SUCCESS)
       {
          // Display all ODBC errors for this stmt
          return(db.DispAllErrors(db.henv, db.hdbc, hstmt));
       }

### wxDb::GetPassword

char * GetPassword()

Returns the password used to connect to the datasource.

### wxDb::GetTableCount

int GetTableCount()

Returns the number of wxDbTable() instances currently using this data source connection.

### wxDb::GetUsername

char * GetUsername()

Returns the user name used to access the datasource.

### wxDb::Grant

bool Grant(int privileges, char *tableName, char *userList = "PUBLIC")

Use this member function to GRANT privileges to users for accessing tables in the datasource.

Parameters

privileges

Use this argument to select which privileges you want to grant. Pass DB_GRANT_ALL to grant all privileges. To grant individual privileges pass one or more of the following OR'd together:

             DB_GRANT_SELECT  = 1
             DB_GRANT_INSERT  = 2
             DB_GRANT_UPDATE  = 4
             DB_GRANT_DELETE  = 8
             DB_GRANT_ALL     = DB_GRANT_SELECT | DB_GRANT_INSERT |
                                DB_GRANT_UPDATE | DB_GRANT_DELETE

tableName

The name of the table you wish to grant privileges on.

userList

A comma delimited list of users to grant the privileges to. If this argument is not passed in, the privileges will be given to the general PUBLIC.

Remarks

Some databases require user names to be specified in all capital letters (i.e. Oracle). This function does not automatically capitalize the user names passed in the comma-separated list. This is the responsibility of the calling routine.

Example

       db.Grant(DB_GRANT_SELECT | DB_GRANT_INSERT, "PARTS", "mary, sue");

### wxDb::IsFwdOnlyCursors

bool IsFwdOnlyCursors()

Indicates whether this connection to the datasource only allows forward scrolling cursors or not. This state is set at connection creation time.

Remarks

Added as of wxWindows v2.4 release, this function is a renamed version of wxDb::FwdOnlyCursors() to match the normal wxWindows naming conventions for class member functions.

This function is not available in versions prior to v2.4. You should use wxDb::FwdOnlyCursors for wxWindows versions priori to 2.4.

See also

wxDb::wxDb, wxDbGetConnection

### wxDb::IsOpen

bool IsOpen()

Indicates whether the database connection to the datasource is currently opened.

### wxDb::Open

bool Open(char *Dsn, char *Uid, char *AuthStr)

Parameters

Dsn

Data source name. The name of the ODBC data source as assigned when the data source is initially set up through the ODBC data source manager.

Uid

User ID. The name (ID) of the user you wish to connect as to the data source. The user name (ID) determines what objects you have access to in the datasource and what datasource privileges you have. Privileges include being able to create new objects, update objects, delete objects and so on. Users and privileges are normally administered by the database administrator.

AuthStr

The password associated witht the Uid.

Remarks

After a wxDb instance is created, it must then be opened. When opening a data source, there must be hree pieces of information passed. The data source name, user name (ID) and the password for the user. No database activity on the data source can be performed until it is opened. This would normally be done at program startup and the data source would remain open for the duration of the program run. Note: It is possible to have multiple data sources open at the same time to support distributed database connections.

Example

       wxDb sampleDB(Db.Henv);
       if (!sampleDB.Open("Oracle 7.1 HP/UX", "gtasker", "myPassword"))
       {
          // Error opening data source
       }

### wxDb::RollbackTrans

bool RollbackTrans()

Function to "rollback" changes made to the database. After an insert/update/delete, the operation may be "undone" by issuing this command any time before a wxDb::CommitTrans is called on the database connection.

Remarks

Transactions begin implicitly as soon as you make a change to the database. At any time thereafter, you can save your work to the database (using wxDb::CommitTrans) or undo all of your changes using this function.

Calling this member function rolls back ALL open (uncommitted) transactions on this ODBC connection.

See also

wxDb::CommitTrans for a special note on cursors

### wxDb::SetSqlLogging

bool SetSqlLogging(wxDbSqlLogState state, const wxChar *filename = SQL_LOG_FILENAME, bool append = FALSE)

Parameters

state

Either sqlLogOFF or sqlLogON (see enum wxDbSqlLogState). Turns logging of SQL commands sent to the data source OFF or ON.

filename

OPTIONAL. Name of the file to which the log text is to be written.

append

OPTIONAL. Whether the file is appended to or overwritten.

Remarks

When called with sqlLogON, all commands sent to the data source engine are logged to the file specified by filename. Logging is done by embedded WriteSqlLog() calls in the database member functions, or may be manually logged by adding calls to WriteSqlLog() in your own source code.

When called with sqlLogOFF, the logging file is closed, and any calls to WriteSqlLog() are ignored.

### wxDb::TableExists

bool TableExists(const char *tableName, const char *userID=NULL, const char *path=NULL)

Checks the ODBC data source for the existence of a table. If a userID is specified, then the table must be accessible by that user (user must have at least minimal privileges to the table).

Parameters

tableName

Name of the table to check for the existence of

userID

Owner of the table. Specify a userID when the datasource you are connected to allows multiple unique tables with the same name to be owned by different users. userID is evaluated as follows:

             userID == NULL  ... UserID is ignored (DEFAULT)
             userID == ""    ... UserID set equal to 'this->uid'
             userID != ""    ... UserID set equal to 'userID'

Remarks

tableName may refer to a table, view, alias or synonym.

This function does not indicate whether or not the user has privileges to query or perform other functions on the table.

### wxDb::TranslateSqlState

int TranslateSqlState(const wxChar *SQLState)

Parameters

SQLState

Converts an ODBC sqlstate to an internal error code.

Return value

Returns the internal class DB_ERR code. See wxDb::DB_STATUS definition.

### wxDb::WriteSqlLog

bool WriteSqlLog(const wxChar *logMsg)

Parameters

logMsg

Free form string to be written to the log file.

Remarks

Very useful debugging tool that may be turned on/off during run time. The passed in string logMsg will be written to a log file if SQL logging is turned on (see wxDb::SetSqlLogging for details on turning logging on/off).

Return value

If SQL logging is off when a call to WriteSqlLog() is made, or there is a failure to write the log message to the log file, the function returns FALSE without performing the requested log, otherwise TRUE is returned.

See also

wxDb::SetSqlLogging

### wxDb::Dbms

wxDBMS Dbms()

Remarks

The return value will be of the enumerated type wxDBMS. This enumerated type contains a list of all the currently tested and supported databases.

Additional databases may be work with these classes, but these databases returned by this function have been tested and confirmed to work with these ODBC classes.

enum wxDBMS includes:

          dbmsUNIDENTIFIED
          dbmsORACLE
          dbmsSYBASE_ASA
          dbmsSYBASE_ASE
          dbmsMY_SQL_SERVER
          dbmsMY_SQL
          dbmsPOSTGRES
          dbmsACCESS
          dbmsDBASE
          dbmsINFORMIX

There are known issues with conformance to the ODBC standards with several datasources listed above. Please see the overview for specific details on which datasource have which issues.

Return value

The return value will indicate which of the supported datasources is currently connected to by this connection. In the event that the datasource is not recognized, a value of 'dbmsUNIDENTIFIED' is returned.

### wxDb::SetDebugErrorMessages

void SetDebugErrorMessages(bool state)

state

Either TRUE (debug messages are displayed) or FALSE (debug messages are not displayed.

Remarks

Turns on/off debug error messages from the ODBC class library. When this function is passed TRUE, errors are reported to the user automatically in a text or pop-up dialog when an ODBC error occurs. When passed FALSE, errors are silently handled.

When compiled in release mode (FINAL=1), this setting has no affect.

See also

wxDb constructor

### wxDb::LogError

void LogError(const char *errMsg const char *SQLState=0)

errMsg

Free-form text to display describing the error to be logged.

SQLState

Native SQL state error

Remarks

Calling this function will enter a log message in the error list maintained for the database connection. This log message is free form and can be anything the programmer wants to enter in the error list.

If SQL logging is turned on, the call to this function will also log the text into the SQL log file.

See also

wxDb::WriteSqlLog