wxdba wxdb instance is a connection to an odbc datasource which may be opened, closed, and re-opened an unlimited number of times. a database connection allows function to be performed directly on the datasource, as well as allowing access to any tables/views defined in the datasource to which the user has sufficient privileges. see the database classes overview for an introduction to using the odbc classes. 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.
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(s) are 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 typeenumerated types associated non-class functions wxdb::wxdb wxdb::catalog wxdb::close wxdb::committrans wxdb::createview wxdb::dbms wxdb::dispallerrors wxdb::dispnexterror wxdb::dropview wxdb::escapesqlchars wxdb::execsql wxdb::fwdonlycursors wxdb::getcatalog wxdb::getcolumncount wxdb::getcolumns wxdb::getdata wxdb::getdatabasename wxdb::getdatasourcename 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::logerror wxdb::modifycolumn wxdb::open wxdb::rollbacktrans wxdb::setdebugerrormessages wxdb::setsqllogging wxdb::sqlcolumnname wxdb::sqltablename wxdb::tableexists wxdb::tableprivileges wxdb::translatesqlstate wxdb::writesqllog
enumerated typesenumerated types enum wxdbsqllogstate
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.
see the remarks in wxdb::dbms for exceptions/issues with each of these database engines. public member variables sword wxdb::cberrormsg
int wxdb::db_status
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
wxchar dbmsname[40] - name of the dbms product wxchar dbmsver[64] - version # of the dbms product wxchar drivername[40] - driver name wxchar odbcver[60] - odbc version of the driver wxchar drvmgrodbcver[60] - odbc version of the driver manager wxchar driverver[60] - driver version wxchar servername[80] - server name, typically a connect string wxchar databasename[128] - database filename wxchar outerjoins[2] - does datasource support outer joins wxchar 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 wxchar 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 requestwxchar wxdb::errorlist[db_max_error_history][db_max_error_msg_len]
wxchar wxdb::errormsg[sql_max_message_length]
sdword wxdb::nativeerror
wxchar wxdb::sqlstate[20]
remarks default cursor scrolling is defined by wxodbc_fwd_only_cursors in setup.h when the wxwidgets library is built. this behavior can be overridden when an instance of a wxdb is created (see wxdb constructor). default setting of this value true, as not all databases/drivers support both types of cursors. see also wxdbcolfor, wxdbcolinf, wxdbtable, wxdbtableinf, wxdbinf
associated non-class functionsthe following functions are used in conjunction with the wxdb class. void wxdbcloseconnections() remarks closes all cached connections that have been made through use of the wxdbgetconnection function. note: these connections are closed regardless of whether they are in use or not. this function should only be called after the program has finished using the connections and all wxdbtable instances that use any of the connections have been closed. this function performs a wxdb::committrans on the connection before closing it to commit any changes that are still pending, as well as to avoid any function sequence errors upon closing each connection. int wxdbconnectionsinuse() remarks returns a count of how many database connections are currently free ( not being used) that have been cached through use of the wxdbgetconnection function. bool wxdbfreeconnection(wxdb *pdb) remarks searches the list of cached database connections connection for one matching the passed in wxdb instance. if found, that cached connection is freed. freeing a connection means that it is marked as available (free) in the cache of connections, so that a call to wxdbgetconnection is able to return a pointer to the wxdb instance for use. freeing a connection does not close the connection, it only makes the connection available again. wxdb * wxdbgetconnection(wxdbconnectinf *pdbconfig, bool fwdonlycursors=(bool)wxodbc_fwd_only_cursors) remarks this function is used to request a "new" wxdb instance for use by the program. the wxdb instance returned is also opened (see wxdb::open). this function (along with wxdbfreeconnection() and wxdbcloseconnection()) maintain a cache of wxdb instances for user/re-use by a program. when a program needs a wxdb instance, it may call this function to obtain a wxdb instance. if there is a wxdb instance in the cache that is currently unused that matches the connection requirements specified in 'pdbconfig' then that cached connection is marked as no longer being free, and a pointer to the wxdb instance is returned. if there are no connections available in the cache that meet the requirements given in 'pdbconfig', then a new wxdb instance is created to connect to the datasource specified in 'pdbconfig' using the userid and password given in 'pdbconfig'. note: the caching routine also uses the wxdb::open connection datatype copying code. if the call to wxdbgetconnection() requests a connection to a datasource, and there is not one available in the cache, a new connection is created. but when the connection is opened, instead of polling the datasource over again for its datatypes, if a connection to the same datasource (using the same userid/password) has already been done previously, the new connection skips querying the datasource for its datatypes, and uses the same datatypes determined previously by the other connection(s) for that same datasource. this cuts down greatly on network traffic, database load, and connection creation time. when the program is done using a connection created through a call to wxdbgetconnection(), the program should call wxdbfreeconnection() to release the wxdb instance back to the cache. do not delete the wxdb instance! deleting the wxdb instance returned can cause a crash/memory corruption later in the program when the cache is cleaned up. when exiting the program, call wxdbcloseconnections() to close all the cached connections created by calls to wxdbgetconnection(). const wxchar * wxdblogextendederrormsg(const wxchar *usertext, wxdb *pdb, wxchar *errfile, int errline) writes a message to the wxlog window (stdout usually) when an internal error situation occurs. bool wxdbsqllog(wxdbsqllogstate state, const wxstring &filename = sql_log_filename) remarks this function sets the sql log state for all open wxdb objects bool wxdbgetdatasource(henv henv, wxchar *dsn, sword dsnmax, wxchar *dsdesc, sword dsdescmax, uword direction = sql_fetch_next) remarks this routine queries the odbc driver manager for a list of available datasources. repeatedly call this function to obtain all the datasources available through the odbc driver manager on the current workstation.
wxarraystring strarray; while (wxdbgetdatasource(dbconnectinf.gethenv(), dsn, sql_max_dsn_length+1, dsdesc, 255)) strarray.add(dsn);members
wxdb::wxdbwxdb() default constructor. wxdb(const henv &ahenv, bool fwdonlycursors=(bool)wxodbc_fwd_only_cursors) constructor, used to create an odbc connection to a datasource. parameters ahenv
fwdonlycursors
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.gethenv()); if (!sampledb.open(connectinf.getdsn(), connectinf.getuserid(), connectinf.getpassword())) { // error opening datasource }see also
wxdb::catalogbool catalog(wxchar * userid, const wxstring &filename = sql_catalog_filename) allows a data "dictionary" of the datasource to be created, dumping pertinent information about all data tables to which the user specified in userid has access. parameters userid
filename
return value returns true if the catalog request was successful, or false if there was some reason that 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::closevoid 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 datasource. 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 datasource sampledb.committrans(); // delete any remaining wxdbtable objects allocated with new delete parts; // close the wxdb connection when finished with it sampledb.close(); wxdb::committransbool 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 with an insert/update/delete, or any other direct sql command that performs one of these operations against the datasource. at any time thereafter, to save the changes to disk permanently, "commit" them by calling this function. calling this member function commits all open transactions on this odbc connection. for example, if three different wxdbtable instances used the same connection to the datasource, committing changes made on one of those wxdbtable instances commits any pending transactions on all three wxdbtable instances. until a call to wxdb::committrans() is made, no other user or cursor is able to see any changes made to the row(s) that have been inserted/modified/deleted. 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 is database dependent, and with some databases this behavior can be controlled through management functions. this means you would need to requery the datasource before you can perform any additional work using this cursor. this is only necessary however if the datasource closes the cursor after a commit or rollback. use the wxdbtable::iscursorclosedoncommit member function to determine the datasource's transaction behavior. note, in many situations it is very inefficient to assume the cursor is closed and always requery. this could put a significant, unnecessary load on datasources that leave the cursors open after a transaction.
wxdb::createviewbool createview(const wxstring & viewname, const wxstring & collist, const wxstring &psqlstmt) creates a sql view of one or more tables in a single datasource. note that this function will only work against databases which support views (currently only oracle as of november 21 2000). parameters viewname
collist
psqlstmt
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 datasource which does support views. example
// incomplete code sample db.createview("parts_sd1", "pn, pd, qty", "select part_num, 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::dbmswxdbms 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 work with these classes, but the databases returned by this function have been tested and confirmed to work with these odbc classes. possible values returned by this function can be viewed in the enumerated types section of wxdb. there are known issues with conformance to the odbc standards with several datasources supported by the wxwidgets odbc classes. 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::dispallerrorsbool dispallerrors(henv ahenv, hdbc ahdbc = sql_null_hdbc, hstmt ahstmt = sql_null_hstmt) used to log all database errors that occurred as a result of an executed database command. this logging is automatic and 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
ahdbc
ahstmt
remarks this member function will log all of the odbc error messages for the last odbc function call that was made. this function is normally used internally within the odbc class library, but can be used programmatically after calling odbc functions directly (i.e. sqlfreeenv()). return value the function always returns false, so a call to this function can be made in the return statement of a code block in the event of a failure to perform an action (see the example below). 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::dispnexterrorvoid dispnexterror() remarks this function is normally used internally within the odbc class library. it could be used programmatically after 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 (wxstrcmp(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::dropviewbool dropview(const wxstring &viewname) drops the data table view named in 'viewname'. parameters viewname
remarks if the view does not exist, this function will return true. note that views are not supported with all datasources.
wxdb::escapesqlcharswxstring escapesqlchars(const wxstring& value) this function is used internally by wxwidgets while building sql statements. it has been provided to help users who wish to explicity construct sql statements to be sent to the server. the function takes the value passed and returns it with any special characters escaped. which characters are considered special depends on what type of datasource the object is connected to. for example, most database servers use a backslash as the escape character; if the value passed contains a backlash it will be replaced with a double backslash before it is passed to the server. this function can be used to avoid passing statements with syntax errors to the server as well as prevent sql injection attacks. parameters value
wxdb::execsqlbool execsql(const wxstring &psqlstmt) bool execsql(const wxstring &psqlstmt, wxdbcolinf **columns, short &numcols) 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. to get column amount and column names or other information about returned columns, pass 'columns' and 'numcols' parameters to the function also. parameters psqlstmt
columns
numcols
remarks this member extends the wxdb class and allows you to build and execute any valid sql statement against the datasource. this allows you to extend the class library by being able to issue any sql statement that the datasource is capable of processing. see also
wxdb::fwdonlycursorsbool isfwdonlycursors() older form (pre-2.3/2.4 of wxwidgets) of the wxdb::isfwdonlycursors. this method is provided for backward compatibility only. the method wxdb::isfwdonlycursors should be used in place of this method. wxdbinf * getcatalog(const wxchar *userid)
wxdb::getcatalogwxdbinf * getcatalog(const wxchar *userid) returns a wxdbinf pointer that points to the catalog (datasource) 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
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 to the connected user (permissions apply) via this connection will be returned.
wxdb::getcolumncountint getcolumncount(const wxstring &tablename, const wxchar *userid) parameters tablename
userid
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, this function will return a -1.
wxdb::getcolumnswxdbcolinf * getcolumns(const wxstring &tablename, uword *numcols, const wxchar *userid=null) wxdbcolinf * getcolumns(wxchar *tablename[], const wxchar *userid) parameters tablename
userid == null ... userid is ignored (default) userid == "" ... userid set equal to 'this->uid' userid != "" ... userid set equal to 'userid'return value this function returns a pointer to an array of wxdbcolinf structures, allowing you to obtain information regarding the columns of the named table(s). if no columns were found, or an error occurred, this pointer will be 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, including those used by any wxdbtable instances that use this wxdb instance. this function should use its own wxdb instance to avoid undesired unbinding of columns.
see also example
wxchar *tablelist[] = {"parts", 0}; wxdbcolinf *colinf = pdb->getcolumns(tablelist); if (colinf) { // use the column inf ....... // destroy the memory delete [] colinf; } wxdb::getdatabool getdata(uword colnumber, 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 colnumber
see also 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 the row returned by the call to ::getnext() // and return 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 this function must request the columns in ordinal sequence (1,2,3 or 1,3 or 2,3).
wxdb::getdatabasenameconst wxchar * getdatabasename() returns the name of the database engine.
wxdb::getdatasourcenameconst wxstring & getdatasourcename() returns the odbc datasource name.
wxdb::gethdbchdbc gethdbc() returns the odbc handle to the database connection.
wxdb::gethenvhenv gethenv() returns the odbc environment handle.
wxdb::gethstmthstmt gethstmt() returns the odbc statement handle associated with this database connection.
wxdb::getkeyfieldsint getkeyfields(const wxstring &tablename, wxdbcolinf *colinf, uword numcolumns) 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
return value currently always returns true. see also
wxdb::getnextbool getnext() called after executing a query, this function requests the next row in the result set after the current position of the cursor. see also
wxdb::getnexterrorbool getnexterror(henv ahenv, hdbc ahdbc = sql_null_hdbc, hstmt ahstmt = sql_null_hstmt) parameters ahenv
example
if (sqlexecdirect(hstmt, (uchar far *) psqlstmt, sql_nts) != sql_success) { return(db.getnexterror(db.henv, db.hdbc, hstmt)); }see also wxdb::dispnexterror, wxdb::dispallerrors
wxdb::getpasswordconst wxstring & getpassword() returns the password used to establish this connection to the datasource.
wxdb::gettablecountint gettablecount() returns the number of wxdbtable() instances currently using this datasource connection.
wxdb::getusernameconst wxstring & getusername() returns the user name (uid) used to establish this connection to the datasource.
wxdb::grantbool grant(int privileges, const wxstring &tablename, const wxstring &userlist = "public") use this member function to grant privileges to users for accessing tables in the datasource. parameters privileges
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_deletetablename
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. the currently logged in user must have sufficient grantor privileges for this function to be able to successfully grant the indicated privileges. example
db.grant(db_grant_select | db_grant_insert, "parts", "mary, sue"); wxdb::isfwdonlycursorsbool isfwdonlycursors() this setting indicates whether this database connection was created as being capable of using only forward scrolling cursors. this function does not indicate if the odbc driver or datasource supports backward scrolling cursors. there is no standard way of detecting if the driver or datasource can support backward scrolling cursors. if a wxdb instance was created as being capable of only forward scrolling cursors, then even if the datasource and odbc driver support backward scrolling cursors, tables using this database connection would only be able to use forward scrolling cursors. the default setting of whether a wxdb connection to a database allows forward-only or also backward scrolling cursors is defined in setup.h by the value of wxodbc_fwd_only_cursors. this default setting can be overridden when the wxdb connection is initially created (see wxdb constructor and wxdbgetconnection). return value returns true if this datasource connection is defined as using only forward scrolling cursors, or false if the connection is defined as being allowed to use backward scrolling cursors and their associated functions (see note above). remarks added as of wxwidgets v2.4 release, this function is a renamed version of wxdb::fwdonlycursors() to match the normal wxwidgets naming conventions for class member functions. this function is not available in versions prior to v2.4. you should use wxdb::fwdonlycursors for wxwidgets versions prior to 2.4. see also wxdb constructor, wxdbgetconnection
wxdb::isopenbool isopen() indicates whether the database connection to the datasource is currently opened. remarks this function may indicate that the database connection is open, even if the call to wxdb::open may have failed to fully initialize the connection correctly. the connection to the database is open and can be used via the direct sql commands, if this function returns true. other functions which depend on the wxdb::open to have completed correctly may not function as expected. the return result from wxdb::open is the only way to know if complete initialization of this wxdb connection was successful or not. see wxdb::open for more details on partial failures to open a connection instance.
wxdb::logerrorvoid logerror(const wxstring &errmsg const wxstring &sqlstate="") errmsg
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::modifycolumnvoid modifycolumn(const wxstring &tablename const wxstring &columnname int datatype ulong columnlength=0 const wxstring &optionalparam="") used to change certain properties of a column such as the length, or whether a column allows nulls or not. tablename
remarks cannot be used to modify the precision of a numeric column, therefore 'columnlength' is ignored unless the datatype is db_data_type_varchar. some datasources do not allow certain properties of a column to be changed if any rows currently have data stored in that column. those datasources that do allow columns to be changed with data in the rows many handle truncation and/or expansion in different ways. please refer to the reference material for the datasource being used for behavioral descriptions. example
ok = pdb->modifycolumn("contacts", "address2", db_, coldefs[j].szdataobj, wxt("not null")); wxdb::openbool open(const wxstring &dsn, const wxstring &uid, const wxstring &authstr, bool failondatatypeunsupported) bool open(const wxstring &inconnectstr, bool failondatatypeunsupported) bool open(wxdbconnectinf *dbconnectinf, bool failondatatypeunsupported) bool open(wxdb *copydb) opens a connection to the datasource, sets certain behaviors of the datasource to confirm to the accepted behaviors (e.g. cursor position maintained on commits), and queries the datasource for its representations of the basic datatypes to determine the form in which the data going to/from columns in the data tables are to be handled. the second form of this function, which accepts a "wxdb *" as a parameter, can be used to avoid the overhead (execution time, database load, network traffic) which are needed to determine the data types and representations of data that are necessary for cross-datasource support by these classes. normally the first form of the wxdb::open() function will open the connection and then send a series of queries to the datasource asking it for its representation of data types, and all the features it supports. if one connection to the datasource has already been made previously, the information gathered when that connection was created can just be copied to any new connections to the same datasource by passing a pointer to the first connection in as a parameter to the wxdb::open() function. note that this new connection created from the first connections information will use the same dsn/uid/authstr as the first connection used. parameters dsn
remarks after a wxdb instance is created, it must then be opened. when opening a datasource, there must be three pieces of information passed. the data source name, user name (id) and the password for the user. no database activity on the datasource can be performed until the connection is opened. this is normally done at program startup and the datasource remains open for the duration of the program/module run. it is possible to have connections to multiple datasources open at the same time to support distributed database connections by having separate instances of wxdb objects that use either the same or different dsn/uid/authstr settings. if this function returns a value of false, it does not necessarily mean that the connection to the datasource was not opened. it may mean that some portion of the initialization of the connection failed (such as a datatype not being able to be determined how the datasource represents it). to determine if the connection to the database failed, use the wxdb::isopen function after receiving a false result back from this function to determine if the connection was opened or not. if this function returns false, but wxdb::isopen returns true, then direct sql commands may be passed to the database connection and can be successfully executed, but use of the datatypes (such as by a wxdbtable instance) that are normally determined during open will not be possible.
the dsn, uid, and authstr string pointers that are passed in are copied. not the strings themselves, only the pointers. the calling routine must maintain the memory for these three strings for the life of the wxdb instance.
example
wxdb sampledb(dbconnectinf.gethenv()); if (!sampledb.open("oracle 7.1 hp/ux", "gtasker", "mypassword")) { if (sampledb.isopen()) { // connection is open, but the initialization of // datatypes and parameter settings failed } else { // error opening datasource } } wxdb::rollbacktransbool rollbacktrans() function to "undo" 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. the transaction continues until either a commit or rollback is executed. calling wxdb::rollbacktrans() will result in all changes done using this database connection that have not already been committed to be "undone" back to the last commit/rollback that was successfully executed.
calling this member function rolls back all open (uncommitted) transactions on this odbc connection, including all wxdbtable instances that use this connection.
see also wxdb::committrans for a special note on cursors
wxdb::setdebugerrormessagesvoid setdebugerrormessages(bool state) state
remarks turns on/off debug error messages from the odbc class library. when this function is passed true, errors are reported to the user/logged 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::setsqlloggingbool setsqllogging(wxdbsqllogstate state, const wxstring &filename = sql_log_filename, bool append = false) parameters state
remarks when called with sqllogon, all commands sent to the datasource engine are logged to the file specified by filename. logging is done by embedded wxdb::writesqllog calls in the database member functions, or may be manually logged by adding calls to wxdb::writesqllog in your own source code. when called with sqllogoff, the logging file is closed, and any calls to wxdb::writesqllog are ignored.
wxdb::sqlcolumnnameconst wxstring sqlcolumnname(const wxchar * colname) returns the column name in a form ready for use in sql statements. in most cases, the column name is returned verbatim. but some databases (e.g. ms access, sql server, msde) allow for spaces in column names, which must be specially quoted. for example, if the datasource allows spaces in the column name, the returned string will have the correct enclosing marks around the name to allow it to be properly included in a sql statement for the dbms that is currently connected to with this connection. parameters colname
see also
wxdb::sqltablenameconst wxstring sqltablename(const wxchar * tablename) returns the table name in a form ready for use in sql statements. in most cases, the table name is returned verbatim. but some databases (e.g. ms access, sql server, msde) allow for spaces in table names, which must be specially quoted. for example, if the datasource allows spaces in the table name, the returned string will have the correct enclosing marks around the name to allow it to be properly included in a sql statement for the data source that is currently connected to with this connection. parameters tablename
see also
wxdb::tableexistsbool tableexists(const wxstring &tablename, const wxchar *userid=null, const wxstring &path="") checks the odbc datasource 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
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. use the wxdb::tableprivileges to determine if the user has sufficient privileges or not. see also
wxdb::tableprivilegesbool tableprivileges(const wxstring &tablename, const wxstring &priv, const wxchar *userid=null, const wxchar *schema=null, const wxstring &path="") checks the odbc datasource 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
select : the connected user is permitted to retrieve data for one or more columns of the table. insert : the connected user is permitted to insert new rows containing data for one or more columns into the table. update : the connected user is permitted to update the data in one or more columns of the table. delete : the connected user is permitted to delete rows of data from the table. references : is the connected user permitted to refer to one or more columns of the table within a constraint (for example, a unique, referential, or table check constraint).userid
userid == null ... not allowed! userid == "" ... userid set equal to 'this->uid' userid != "" ... userid set equal to 'userid'schema
schema == null ... any owner (default) schema == "" ... owned by 'this->uid' schema != "" ... owned by userid specified in 'schema'path
remarks the scope of privilege allowed to the connected user by a given table privilege is datasource dependent. for example, the privilege update might allow the connected user to update all columns in a table on one datasource, but only those columns for which the grantor (the user that granted the connected user) has the update privilege on another datasource. looking up a user's privileges to a table can be time consuming depending on the datasource and odbc driver. this time can be minimized by passing a schema as a parameter. with some datasources/drivers, the difference can be several seconds of time difference.
wxdb::translatesqlstateint translatesqlstate(const wxstring &sqlstate) converts an odbc sqlstate to an internal error code. parameters sqlstate
return value returns the internal class db_err code. see wxdb::db_status definition.
wxdb::writesqllogbool writesqllog(const wxstring &logmsg) parameters logmsg
remarks very useful debugging tool that may be turned on/off during run time (see (see wxdb::setsqllogging for details on turning logging on/off). the passed in string logmsg will be written to a log file if sql logging is turned on. 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
|