database classes overviewfollowing is a detailed overview of how to use the wxwidgets odbc classes - wxdb and wxdbtable and their associated functions. these are the odbc classes donated by remstar international, and are collectively referred to herein as the wxodbc classes.
wxdb/wxdbtable wxodbc overview
wxdb/wxdbtable wxodbc overviewthe wxodbc classes were designed for database independence. although sql and odbc both have standards which define the minimum requirements they must support to be in compliance with specifications, different database vendors may implement things slightly differently. one example of this is that oracle requires all user names for the datasources to be supplied in uppercase characters. in situations like this, the wxodbc classes have been written to make this transparent to the programmer when using functions that require database-specific syntax. currently several major databases, along with other widely used databases, have been tested and supported through the wxodbc classes. the list of supported databases is certain to grow as more users start implementing software with these classes, but at the time of the writing of this document, users have successfully used the classes with the following datasources:
an up-to-date list can be obtained by looking in the comments of the function wxdb::dbms in db.cpp, or in the enumerated type wxdbms in db.h. **dbase is not truly an odbc datasource, but there are drivers which can emulate much of the functionality of an odbc connection to a dbase table. see the wxodbc known issues section of this overview for details.
wxodbc where to startfirst, if you are not familiar with sql and odbc, go to your local bookstore and pick up a good book on each. this documentation is not meant to teach you many details about sql or odbc, though you may learn some just from immersion in the subject. if you have worked with non-sql/odbc datasources before, there are some things you will need to un-learn. first some terminology as these phrases will be used heavily in this section of the manual.
before you are able to read data from a data table in a datasource, you must have a connection to the datasource. each datasource connection may be used to open multiple tables all on the same connection (number of tables open are dependent on the driver, datasource configuration and the amount of memory on the client workstation). multiple connections can be opened to the same datasource by the same client (number of concurrent connections is dependent on the driver and datasource configuration). when a query is performed, the client passes the query to the odbc driver, and the driver then translates it and passes it along to the datasource. the database engine (in most cases - exceptions are text and dbase files) running on the machine hosting the database does all the work of performing the search for the requested data. the client simply waits for a status to come back through the odbc driver from the datasource. depending on the odbc driver, the result set either remains "queued" on the database server side, or is transferred to the machine that the driver is queued on. the client does not receive this data. the client must request some or all of the result set to be returned before any data rows are returned to the client application. result sets do not need to include all columns of every row matching the query. in fact, result sets can actually be joinings of columns from two or more data tables, may have derived column values, or calculated values returned. for each result set, a cursor is maintained (typically by the database) which keeps track of where in the result set the user currently is. depending on the database, odbc driver, and how you configured the wxwidgets odbc settings in setup.h (see wxodbc - compiling), cursors can be either forward or backward scrolling. at a minimum, cursors must scroll forward. for example, if a query resulted in a result set with 100 rows, as the data is read by the client application, it will read row 1, then 2, then 3, etc. with forward only cursors, once the cursor has moved to the next row, the previous row cannot be accessed again without re-querying the datasource for the result set over again. backward scrolling cursors allow you to request the previous row from the result set, actually scrolling the cursor backward. backward scrolling cursors are not supported on all database/driver combinations. for this reason, forward-only cursors are the default in the wxodbc classes. if your datasource does support backward scrolling cursors and you wish to use them, make the appropriate changes in setup.h to enable them (see wxodbc - compiling). for greatest portability between datasources, writing your program in such a way that it only requires forward scrolling cursors is your best bet. on the other hand, if you are focusing on using only datasources that support backward scrolling cursors, potentially large performance benefits can be gained from using them. there is a limit to the number of cursors that can be open on each connection to the datasource, and usually a maximum number of cursors for the datasource itself. this is all dependent on the database. each connection that is opened (each instance of a wxdb) opens a minimum of 5 cursors on creation that are required for things such as updates/deletions/rollbacks/queries. cursors are a limited resource, so use care in creating large numbers of cursors. additional cursors can be created if necessary with the wxdbtable::getnewcursor function. one example use for additional cursors is to track multiple scroll points in result sets. by creating a new cursor, a program could request a second result set from the datasource while still maintaining the original cursor position in the first result set. different than non-sql/odbc datasources, when a program performs an insertion, deletion, or update (or other sql functions like altering tables, etc) through odbc, the program must issue a "commit" to the datasource to tell the datasource that the action(s) it has been told to perform are to be recorded as permanent. until a commit is performed, any other programs that query the datasource will not see the changes that have been made (although there are databases that can be configured to auto-commit). note: with most datasources, until the commit is performed, any cursor that is open on that same datasource connection will be able to see the changes that are uncommitted. check your database's documentation/configuration to verify this before relying on it though. a rollback is basically an undo command on the datasource connection. when a rollback is issued, the datasource will flush all commands it has been told to do since the last commit that was performed. note: commits/rollbacks are done on datasource connections (wxdb instances) not on the wxdbtable instances. this means that if more than one table shares the same connection, and a commit or rollback is done on that connection, all pending changes for all tables using that connection are committed/rolled back.
wxodbc - configuring your system for odbc usebefore you are able to access a datasource, you must have installed and configured an odbc driver. doing this is system specific, so it will not be covered in detail here. but here are a few details to get you started. most database vendors provide at least a minimal odbc driver with their database product. in practice, many of these drivers have proven to be slow and/or incomplete. rumour has it that this is because the vendors do not want you using the odbc interface to their products; they want you to use their applications to access the data. whatever the reason, for database-intensive applications, you may want to consider using a third-party odbc driver for your needs. one example of a third-party set of odbc drivers that has been heavily tested and used is rogue wave's drivers. rogue wave has drivers available for many different platforms and databases. under microsoft windows, install the odbc driver you are planning to use. you will then use the odbc administrator in the control panel to configure an instance of the driver for your intended datasource. note that with all flavors of nt, this configuration can be set up as a system or user dsn (datasource name). configuring it as a system resource will make it available to all users (if you are logged in as 'administrator'), otherwise the datasource will only be available to the user who configured the dsn. under unix, iodbc is used for implementation of the odbc api. to compile the wxodbc classes, you must first obtain iodbc from http://www.iodbc.org and install it. (note: wxwidgets currently includes a version of iodbc.) then you must create the file "~/.odbc.ini" (or optionally create "/etc/odbc.ini" for access for all users on the system). this file contains the settings for your system/datasource. below is an example section of a odbc.ini file for use with the "samples/db" sample program using mysql:
[contacts] trace = off tracefile= stderr driver = /usr/local/lib/libmyodbc.so dsn = contacts server = 192.168.1.13 user = qet password = port = 3306 wxodbc - compilingthe wxwidgets setup.h file has several settings in it pertaining to compiling the wxodbc classes.
under ms windows you are required to include the "odbc32.lib" provided by your compiler vendor in the list of external libraries to be linked in. if using the makefiles supplied with wxwidgets, this library should already be included for use with makefile.b32, makefile.vc, and makefile.g95.
more to come
under unix --with-odbc flag for configure
more to come
wxodbc - basic step-by-step guideto use the classes in an application, there are eight basic steps:
following each of these steps is detailed to explain the step, and to hopefully mention as many of the pitfalls that beginning users fall in to when first starting to use the classes. throughout the steps, small snippets of code are provided to show the syntax of performing the step. a complete code snippet is provided at the end of this overview that shows a complete working flow of all these steps (see wxodbc - sample code). define datasource connection information to be able to connect to a datasource through the odbc driver, a program must supply a minimum of three pieces of information: datasource name, user id, and authorization string (password). a fourth piece of information, a default directory indicating where the data file is stored, is required for text and dbase drivers for odbc. the wxwidgets data class wxdbconnectinf exists for holding all of these values, plus some others that may be desired. the 'henv' member is the environment handle used to access memory for use by the odbc driver. use of this member is described below in the "getting a connection to the datasource" section. the 'dsn' must exactly match the datasource name used to configure the odbc datasource (in the odbc administrator (msw only) or in the .odbc.ini file). the 'uid' is the user id that is to be used to log in to the datasource. this user id must already have been created and assigned rights within the datasource to which you are connecting. the user that the connection is establish by will determine what rights and privileges the datasource connection will allow the program to have when using the connection that this connection information was used to establish. some datasources are case sensitive for user ids, and though the wxodbc classes attempt to hide this from you by manipulating whatever data you pass in to match the datasource's needs, it is always best to pass the 'uid' in the case that the datasource requires. the 'authstr' is the password for the user id specified in the 'uid' member. as with the 'uid', some datasources are case sensitive (in fact most are). the wxodbc classes do not try to manage the case of the 'authstr' at all. it is passed verbatim to the datasource, so you must use the case that the datasource is expecting. the 'defaultdir' member is used with file based datasources (i.e. dbase, foxpro, text files). it contains a full path to the location where the data table or file is located. when setting this value, use forward slashes '/' rather than backslashes ' avoid compatibility differences between odbc drivers. the other fields are currently unused. the intent of these fields are that they will be used to write our own odbc administrator type program that will work on both msw and un*x systems, regardless of the datasource. very little work has been done on this to date. get a datasource connection there are two methods of establishing a connection to a datasource. you may either manually create your own wxdb instance and open the connection, or you may use the caching functions provided with the wxodbc classes to create/maintain/delete the connections. regardless of which method you use, you must first have a fully populated wxdbconnectinf object. in the wxdbconnectinf instance, provide a valid dns, uid, and authstr (along with a 'defaultdir' if necessary). before using this though, you must allocate an environment handle to the 'henv' member.
wxdbconnectinf dbconnectinf; dbconnectinf.setdsn("mydsn"); dbconnectinf.setuserid("myusername"); dbconnectinf.setpassword("mypassword"); dbconnectinf.setdefaultdir("");to allocate an environment handle for the odbc connection to use, the wxdbconnectinf class has a datasource independent method for creating the necessary handle:
if (dbconnectinf.allochenv()) { wxmessagebox("unable to allocate an odbc environment handle", "db connection error", wxok | wxicon_exclamation); return; }when the wxdbconnectinf::allochenv() function is called successfully, a value of true will be returned. a value of false means allocation failed, and the handle will be undefined. a shorter form of doing the above steps is encapsulated into the long form of the constructor for wxdbconnectinf.
wxdbconnectinf *dbconnectinf; dbconnectinf = new wxdbconnectinf(null, "mydsn", "myusername", "mypassword", "");this shorthand form of initializing the constructor passes a null for the sql environment handle, telling the constructor to allocate a handle during construction. this handle is also managed for the life of wxdbconnectinf instance, and is freed automatically upon destruction of the instance. once the wxdbconnectinf instance is initialized, you are ready to connect to the datasource. to manually create datasource connections, you must create a wxdb instance, and then open it.
wxdb *db = new wxdb(dbconnectinf->gethenv()); opened = db->open(dbconnectinf);the first line does the house keeping needed to initialize all the members of the wxdb class. the second line actually sends the request to the odbc driver to open a connection to its associated datasource using the parameters supplied in the call to wxdb::open. a more advanced form of opening a connection is to use the connection caching functions that are included with the wxodbc classes. the caching mechanisms perform the same functions as the manual approach to opening a connection, but they also manage each connection they have created, re-using them and cleaning them up when they are closed, without you needing to do the coding. to use the caching function wxdbgetconnection to get a connection to a datasource, simply call it with a single parameter of the type wxdbconnectinf:
db = wxdbgetconnection(dbconnectinf);the wxdb pointer that is returned is both initialized and opened. if something failed in creating or opening the connection, the return value from wxdbgetconnection will be null. the connection that is returned is either a new connection, or it is a "free" connection from the cache of connections that the class maintains that was no longer in use. any wxdb instance created with a call to wxdbgetconnection is recorded in a linked list of established connections. when a program is finished with a connection, a call to wxdbfreeconnection is made, and the datasource connection will then be tagged as free, making it available for the next call to wxdbgetconnection that needs a connection using the same connection information (dsn, uid, authstr). the cached connections remain cached until a call to wxdbcloseconnections is made, at which time all cached connections are closed and deleted. besides the obvious advantage of using the single command caching routine to obtain a datasource connection, using cached connections can be quite a performance boost as well. each time that a new connection is created (not retrieved from the cache of free connections), the wxodbc classes perform many queries against the datasource to determine the datasource's datatypes and other fundamental behaviours. depending on the hardware, network bandwidth, and datasource speed, this can in some cases take a few seconds to establish the new connection (with well-balanced systems, it should only be a fraction of a second). re-using already established datasource connections rather than creating/deleting, creating/deleting connections can be quite a time-saver. another time-saver is the "copy connection" features of both wxdb::open and wxdbgetconnection. if manually creating a wxdb instance and opening it, you must pass an existing connection to the wxdb::open function yourself to gain the performance benefit of copying existing connection settings. the wxdbgetconnection function automatically does this for you, checking the dsn, uid, and authstr parameters when you request a connection for any existing connections that use those same settings. if one is found, wxdbgetconnection copies the datasource settings for datatypes and other datasource specific information that was previously queried, rather than re-querying the datasource for all those same settings. one final note on creating a connection. when a connection is created, it will default to only allowing cursor scrolling to be either forward only, or both backward and forward scrolling. the default behavior is determined by the setting wxodbc_fwd_only_cursors in setup.h when you compile the wxwidgets library. the library default is to only support forward scrolling cursors only, though this can be overridden by parameters for wxdb() constructor or the wxdbgetconnection function. all datasources and odbc drivers must support forward scrolling cursors. many datasources support backward scrolling cursors, and many odbc drivers support backward scrolling cursors. before planning on using backward scrolling cursors, you must be certain that both your datasource and odbc driver fully support backward scrolling cursors. see the small blurb about "scrolling cursors" in the definitions at the beginning of this overview, or other details of setting the cursor behavior in the wxdb class documentation. create table definition data can be accessed in a datasource's tables directly through various functions of the wxdb class (see wxdb::getdata). but to make life much simpler, the wxdbtable class encapsulates all of the sql specific api calls that would be necessary to do this, wrapping it in an intuitive class of apis. the first step in accessing data in a datasource's tables via the wxdbtable class is to create a wxdbtable instance.
table = new wxdbtable(db, tablename, numtablecolumns, "", !wxdb_query_only, "");when you create the instance, you indicate the previously established datasource connection to be used to access the table, the name of the primary table that is to be accessed with the datasource's tables, how many columns of each row are going to be returned, the name of the view of the table that will actually be used to query against (works with oracle only at this time), whether the data returned is for query purposes only, and finally the path to the table, if different than the path specified when connecting to the datasource. each of the above parameters are described in detail in the wxdbtable class' description, but one special note here about the fifth parameter - the queryonly setting. if a wxdbtable instance is created as wxdb_query_only, then no inserts/deletes/updates can be performed using this instance of the wxdbtable. any calls to wxdb::committrans or wxdb::rollbacktrans against the datasource connection used by this wxdbtable instance are ignored by this instance. if the wxdbtable instance is created with !wxdb_query_only as shown above, then all the cursors and other overhead associated with being able to insert/update/delete data in the table are created, and thereby those operations can then be performed against the associated table with this wxdbtable instance. if a table is to be accessed via a wxdbtable instance, and the table will only be read from, not written to, there is a performance benefit (not as many cursors need to be maintained/updated, hence speeding up access times), as well as a resource savings due to fewer cursors being created for the wxdbtable instance. also, with some datasources, the number of simultaneous cursors is limited. when defining the columns to be retrievable by the wxdbtable instance, you can specify anywhere from one column up to all columns in the table.
table->setcoldefs(0, "first_name", db_data_type_varchar, firstname, sql_c_wxchar, sizeof(firstname), true, true); table->setcoldefs(1, "last_name", db_data_type_varchar, lastname, sql_c_wxchar, sizeof(lastname), true, true);notice that column definitions start at index 0 and go up to one less than the number of columns specified when the wxdbtable instance was created (in this example, two columns - one with index 0, one with index 1). the above lines of code "bind" the datasource columns specified to the memory variables in the client application. so when the application makes a call to wxdbtable::getnext (or any other function that retrieves data from the result set), the variables that are bound to the columns will have the column value stored into them. see the wxdbtable::setcoldefs class documentation for more details on all the parameters for this function. the bound memory variables have undefined data in them until a call to a function that retrieves data from a result set is made (e.g. wxdbtable::getnext, wxdbtable::getprev, etc). the variables are not initialized to any data by the wxodbc classes, and they still contain undefined data after a call to wxdbtable::query. only after a successful call to one of the ::getxxxx() functions is made do the variables contain valid data. it is not necessary to define column definitions for columns whose data is not going to be returned to the client. for example, if you want to query the datasource for all users with a first name of 'george', but you only want the list of last names associated with those rows (why return the first_name column every time when you already know it is 'george'), you would only have needed to define one column above. you may have as many wxdbtable instances accessing the same table using the same wxdb instance as you desire. there is no limit imposed by the classes on this. all datasources supported (so far) also have no limitations on this. open the table opening the table is not technically doing anything with the datasource itself. calling wxdbtable::open simply does all the housekeeping of checking that the specified table exists, that the current connected user has at least select privileges for accessing the table, setting up the requisite cursors, binding columns and cursors, and constructing the default insert statement that is used when a new row is inserted into the table (non-wxdb_query_only tables only).
if (!table->open()) { // an error occurred opening (setting up) the table }the only reason that a call to wxdbtable::open is likely to fail is if the user has insufficient privileges to even select the table. other problems could occur, such as being unable to bind columns, but these other reason point to some lack of resource (like memory). any errors generated internally in the wxdbtable::open function are logged to the error log if sql logging is turned on for the classes. use the table to use the table and the definitions that are now set up, we must first define what data we want the datasource to collect in to a result set, tell it where to get the data from, and in which sequence we want the data returned.
// the where clause limits/specifies which rows in the table // are to be returned in the result set table->setwhereclause("first_name = 'george'"); // result set will be sorted in ascending alphabetical // order on the data in the 'last_name' column of each row // if the same last name is in the table for two rows, // sub-sort on the 'age' column table->setorderbyclause("last_name, age"); // no other tables (joins) are used for this query table->setfromclause("");the above lines will be used to tell the datasource to return in the result all the rows in the table whose column "first_name" contains the name 'george' (note the required use of the single quote around the string literal) and that the result set will return the rows sorted by ascending last names (ascending is the default, and can be overridden with the "desc" keyword for datasources that support it - "last_name desc"). specifying a blank where clause will result in the result set containing all rows in the datasource. specifying a blank orderby clause means that the datasource will return the result set in whatever sequence it encounters rows which match the selection criteria. what this sequence is can be hard to determine. typically it depends on the index that the datasource used to find the rows which match the where criteria. beware - relying on the datasource to return data in a certain sequence when you have not provided an orderby clause will eventually cause a problem for your program. databases can be tuned to be cost-based, speed-based, or some other basis for how it gets your result set. in short, if you need your result set returned in a specific sequence, ask for it that way by providing an orderby clause. using an orderby clause can be a performance hit, as the database must sort the items before making the result set available to the client. creating efficient indexes that cause the data to be "found" in the correct orderby sequence can be a big performance benefit. also, in the large majority of cases, the database will be able to sort the records faster than your application can read all the records in (unsorted) and then sort them. let the database do the work for you! notice in the example above, a column that is not included in the bound data columns ('age') will be used to sub-sort the result set. the from clause in this example is blanked, as we are not going to be performing any table joins with this simple query. when the from clause is blank, it is assumed that all columns referenced are coming from the default table for the wxdbtable instance. after the selection criteria have been specified, the program can now ask the datasource to perform the search and create a result set that can be retrieved:
// instruct the datasource to perform a query based on the // criteria specified above in the where/orderby/from clauses. if (!table->query()) { // an error occurred performing the query }typically, when an error occurs when calling wxdbtable::query, it is a syntax problem in the where clause that was specified. the exact sql (datasource-specific) reason for what caused the failure of wxdbtable::query (and all other operations against the datasource can be found by parsing the table's database connection's "errorlist[]" array member for the stored text of the error. when the wxdbtable::query returns true, the database was able to successfully complete the requested query using the provided criteria. this does not mean that there are any rows in the result set, it just mean that the query was successful.
important: the result created by the call to wxdbtable::query can take one of two forms. it is either a snapshot of the data at the exact moment that the database determined the record matched the search criteria, or it is a pointer to the row that matched the selection criteria. which form of behavior is datasource dependent. if it is a snapshot, the data may have changed since the result set was constructed, so beware if your datasource uses snapshots and call wxdbtable::refresh. most larger brand databases do not use snapshots, but it is important to mention so that your application can handle it properly if your datasource does.
to retrieve the data, one of the data fetching routines must be used to request a row from the result set, and to store the data from the result set into the bound memory variables. after wxdbtable::query has completed successfully, the default/current cursor is placed so it is pointing just before the first record in the result set. if the result set is empty (no rows matched the criteria), then any calls to retrieve data from the result set will return false.
wxstring msg; while (table->getnext()) { msg.printf("row #%lu -- first name : %s last name is %s", table->getrownum(), firstname, lastname); wxmessagebox(msg, "data", wxok | wxicon_information, null); }the sample code above will read the next record in the result set repeatedly until the end of the result set has been reached. the first time that wxdbtable::getnext is called right after the successful call to wxdbtable::query, it actually returns the first record in the result set. when wxdbtable::getnext is called and there are no rows remaining in the result set after the current cursor position, wxdbtable::getnext (as well as all the other wxdbtable::getxxxxx() functions) will return false. close the table when the program is done using a wxdbtable instance, it is as simple as deleting the table pointer (or if declared statically, letting the variable go out of scope). typically the default destructor will take care of all that is required for cleaning up the wxdbtable instance.
if (table) { delete table; table = null; }deleting a wxdbtable instance releases all of its cursors, deletes the column definitions and frees the sql environment handles used by the table (but not the environment handle used by the datasource connection that the wxdbtable instance was using). close the datasource connection after all tables that have been using a datasource connection have been closed (this can be verified by calling wxdb::gettablecount and checking that it returns 0), then you may close the datasource connection. the method of doing this is dependent on whether the non-caching or caching method was used to obtain the datasource connection. if the datasource connection was created manually (non-cached), closing the connection is done like this:
if (db) { db->close(); delete db; db = null; }if the program used the wxdbgetconnection function to get a datasource connection, the following is the code that should be used to free the connection(s):
if (db) { wxdbfreeconnection(db); db = null; }note that the above code just frees the connection so that it can be re-used on the next call the wxdbgetconnection. to actually dispose of the connection, releasing all of its resources (other than the environment handle), do the following:
wxdbcloseconnections();release the odbc environment handle once all of the connections that used the odbc environment handle (in this example it was stored in "dbconnectinf.henv") have been closed, then it is safe to release the environment handle:
dbconnectinf->freehenv();or, if the long form of the constructor was used and the constructor was allowed to allocate its own sql environment handle, leaving scope or destruction of the wxdbconnectinf will free the handle automatically.
delete dbconnectinf; remember to never release this environment handle if there are any connections still using the handle.
wxodbc - known issuesas with creating wxwidgets, writing the wxodbc classes was not the simple task of writing an application to run on a single type of computer system. the classes need to be cross-platform for different operating systems, and they also needed to take in to account different database manufacturers and different odbc driver manufacturers. because of all the possible combinations of os/database/drivers, it is impossible to say that these classes will work perfectly with datasource abc, odbc driver xyz, on platform lmn. you may run into some incompatibilities or unsupported features when moving your application from one environment to another. but that is what makes cross-platform programming fun. it also pinpoints one of the great things about open source software. it can evolve! the most common difference between different database/odbc driver manufacturers in regards to these wxodbc classes is the lack of standard error codes being returned to the calling program. sometimes manufacturers have even changed the error codes between versions of their databases/drivers. in all the tested databases, every effort has been made to determine the correct error codes and handle them in the class members that need to check for specific error codes (such as table does not exist when you try to open a table that has not been created yet). adding support for additional databases in the future requires adding an entry for the database in the wxdb::dbms function, and then handling any error codes returned by the datasource that do not match the expected values. databases following is a list of known issues and incompatibilities that the wxodbc classes have between different datasources. an up to date listing of known issues can be seen in the comments of the source for wxdb::dbms. oracle
dbase note: dbase is not a true odbc datasource. you only have access to as much functionality as the driver can emulate.
sybase (all)
sybase (enterprise)
mysql
postgres
db2
unicode with wxodbc classes as of v2.6 of wxwidgets, the wxodbc classes now fully support the compilation and use of the classes in a unicode build of wxwidgets, assuming the compiler and os on which the program will be compiled/run is unicode capable. the one major difference in writing code that can be compiled in either unicode or non-unicode builds that is specific to the wxodbc classes is to use the sql_c_wxchar datatype for string columns rather than sql_c_char or sql_c_wchar.
wxodbc - sample codesimplest example of establishing/opening a connection to an odbc datasource, binding variables to the columns for read/write usage, opening an existing table in the datasource, inserting a record, setting query parameters (where/orderby/from), querying the datasource, reading each row of the result set, deleting a record, releasing the connection, then cleaning up. note: very basic error handling is shown here, to reduce the size of the code and to make it more easily readable. the handleerror() function uses the wxdblogextendederrormsg() function for retrieving database error messages.
// ---------------------------------------------------------------------------- // headers // ---------------------------------------------------------------------------- #include "wx/log.h" // #included to enable output of messages only #include "wx/dbtable.h" // ---------------------------------------------------------------------------- // function used for handling/displaying errors // ---------------------------------------------------------------------------- // very generic error handling function. // if a connection to the database is passed in, then we retrieve all the // database errors for the connection and add them to the displayed message int handleerror(wxstring errmsg, wxdb *pdb=null) { // retrieve all the error message for the errors that occurred wxstring allerrors; if (!pdb == null) // get the database errors and append them to the error message allerrors = wxdblogextendederrormsg(errmsg.c_str(), pdb, 0, 0); else allerrors = errmsg; // do whatever you wish with the error message here // wxlogdebug() is called inside wxdblogextendederrormsg() so this // console program will show the errors in the console window, // but these lines will show the errors in release builds also wxfprintf(stderr, wxt("\n%s\n"), allerrors.c_str()); fflush(stderr); return 1; } // ---------------------------------------------------------------------------- // entry point // ---------------------------------------------------------------------------- int main(int argc, char **argv) { wxdbconnectinf *dbconnectinf = null; // db connection information wxdb *db = null; // database connection wxdbtable *table = null; // data table to access const wxchar tablename[] = wxt("users"); // name of database table const uword numtablecolumns = 2; // number table columns wxchar firstname[50+1]; // column data: "first_name" wxchar lastname[50+1]; // column data: "last_name" wxstring msg; // used for display messages // ----------------------------------------------------------------------- // define the connection handle for the database // ----------------------------------------------------------------------- dbconnectinf = new wxdbconnectinf(null, wxt("contacts-sqlserver"), wxt("sa"), wxt("abk")); // error checking.... if (!dbconnectinf || !dbconnectinf->gethenv()) { return handleerror(wxt("db env error: cannot allocate odbc env handle")); } // ----------------------------------------------------------------------- // get a database connection // ----------------------------------------------------------------------- db = wxdbgetconnection(dbconnectinf); if (!db) { return handleerror(wxt("connection error - cannot get db connection")); } // ----------------------------------------------------------------------- // define the table, and the columns that will be accessed // ----------------------------------------------------------------------- table = new wxdbtable(db, tablename, numtablecolumns, wxt(""), !wxdb_query_only, wxt("")); // // bind the columns that you wish to retrieve. note that there must be // 'numtablecolumns' calls to setcoldefs(), to match the wxdbtable def // // not all columns need to be bound, only columns whose values are to be // returned back to the client. // table->setcoldefs(0, wxt("first_name"), db_data_type_varchar, firstname, sql_c_wxchar, sizeof(firstname), true, true); table->setcoldefs(1, wxt("last_name"), db_data_type_varchar, lastname, sql_c_wxchar, sizeof(lastname), true, true); // ----------------------------------------------------------------------- // create (or recreate) the table in the database // ----------------------------------------------------------------------- if (!table->createtable(true)) //note: no committrans is required { return handleerror(wxt("table creation error: "), table->getdb()); } // ----------------------------------------------------------------------- // open the table for access // ----------------------------------------------------------------------- if (!table->open()) { return handleerror(wxt("table open error: "), table->getdb()); } // ----------------------------------------------------------------------- // insert a new row into the table // ----------------------------------------------------------------------- wxstrcpy(firstname, wxt("julian")); wxstrcpy(lastname, wxt("smart")); if (!table->insert()) { return handleerror(wxt("insertion error: "), table->getdb()); } // must commit the insert to write the data to the db table->getdb()->committrans(); // ----------------------------------------------------------------------- // retrieve rows from the table based on supplied criteria // ----------------------------------------------------------------------- // set the where clause to limit the result set to return // all rows that have a value of 'julian' in the first_name // column of the table. table->setwhereclause(wxt("first_name = 'julian'")); // result set will be sorted in ascending alphabetical // order on the data in the 'last_name' column of each row table->setorderbyclause(wxt("last_name")); // no other tables (joins) are used for this query table->setfromclause(wxt("")); // instruct the datasource to perform a query based on the // criteria specified above in the where/orderby/from clauses. if (!table->query()) { return handleerror(wxt("query error: "), table->getdb()); } // loop through all rows matching the query criteria until // there are no more records to read while (table->getnext()) { msg.printf(wxt("row #%lu -- first name : %s last name is %s"), table->getrownum(), firstname, lastname); // code to display 'msg' here wxlogmessage(wxt("\n%s\n"), msg.c_str()); } // ----------------------------------------------------------------------- // delete a row from the table // ----------------------------------------------------------------------- // select the row which has first_name of 'julian' and last_name // of 'smart', then delete the retrieved row // if (!table->deletewhere(wxt("first_name = 'julian' and last_name = 'smart'"))) { return handleerror(wxt("deletion error: "), table->getdb()); } // must commit the deletion to the database table->getdb()->committrans(); // ----------------------------------------------------------------------- // take care of the odbc class instances that were being used // ----------------------------------------------------------------------- // if the wxdbtable instance was successfully created // then delete it as we are done with it now. wxdelete(table); // free the cached connection // (meaning release it back in to the cache of datasource // connections) for the next time a call to wxdbgetconnection() // is made. wxdbfreeconnection(db); db = null; // ----------------------------------------------------------------------- // cleanup before exiting app // ----------------------------------------------------------------------- // the program is now ending, so we need to close // any cached connections that are still being // maintained. wxdbcloseconnections(); // release the environment handle that was created // for use with the odbc datasource connections wxdelete(dbconnectinf); wxunusedvar(argc); // here just to prevent compiler warnings wxunusedvar(argv); // here just to prevent compiler warnings return 0; } a selection of sql commandsthe following is a very brief description of some common sql commands, with examples. see also
createcreates a table. example:
create table book (booknumber integer primary key , categorycode char(2) default 'ro' not null , title varchar(100) unique , numberofpages smallint , retailpriceamount numeric(5,2) ) insertinserts records into a table. example:
insert into book (booknumber, categorycode, title) values(5, 'hr', 'the lark ascending') selectthe select operation retrieves rows and columns from a table. the criteria for selection and the columns returned may be specified. examples: select * from book selects all rows and columns from table book. select title, retailpriceamount from book where retailpriceamount > 20.0 selects columns title and retailpriceamount from table book, returning only the rows that match the where clause. select * from book where catcode = 'll' or catcode = 'rr' selects all columns from table book, returning only the rows that match the where clause. select * from book where catcode is null selects all columns from table book, returning only rows where the catcode column is null. select * from book order by title selects all columns from table book, ordering by title, in ascending order. to specify descending order, add desc after the order by title clause. select title from book where retailpriceamount >= 20.0 and retailpriceamount <= 35.0 selects records where retailpriceamount conforms to the where expression.
updateupdates records in a table. example: update incident set x = 123 where asset = 'bd34' this example sets a field in column 'x' to the number 123, for the record where the column asset has the value 'bd34'.
|