CodeGuru
Earthweb Search
Forums Wireless Jars Gamelan Developer.com
CodeGuru Navigation
RSS Feeds

RSSAll

RSSVC++/C++

RSS.NET/C#

RSSVB

See more EarthWeb Network feeds

follow us on Twitter

Member Sign In
User ID:
Password:
Remember Me:
Forgot Password?
Not a member?
Click here for more information and to register.

Become a Marketplace Partner

jobs.internet.com

internet.commerce
Partners & Affiliates
















Home >> Visual C++ / C++ >> Data >> Database >> ODBC


Ultra Simple DB Class Interface for ODBC
Rating: none

Mark Henri (view profile)
September 12, 2003

Environment: VC6, Win9x/ME Win NT/2000/XP

Introduction—Opening the Database

The ODBC API has a lot of power and flexibility, but sometimes you just want to get the data without all the effort. Hence, these simple class wrappers. In addition, from insulating you from having to bind buffers and or figure out data type widths and conversions, they have a fairly simple interface. They operate on the premise of dealing with everything as ASCII character data. Oversimplification? You be the judge. Let's get into what some sample code and see how easy it is to get to your data.


(continued)



First we'll open the database...

   CSQLDatabase db;
   if ( ! db.Open( "MPHSample" ) )
   {
      cout << "couldn't open data source name" << endl;
      return 0;
   }

Extracting Data

Next, we'll extract some data from a known table. I kept it to those with last names starting with A so it would be under a screen full.

I'll bet you're already thinking that this should look like an STL container with an iterator. You're right; I'm probably going to write something that looks like that soon. MySQL has a beautiful design that I would probably emulate.

Still, this makes extraction pretty easy. The only thing to watch out for is the ordering; the variables must follow the order of the original SQL statement and be extracted sequentially from the beginning.

   CSQLRecordset rs( db );
   rs << "select name, address1, city, state,"
      " zip from provider";
   rs.SetWhere( "name < 'B'" );    // It's 1 screen full
   rs.SQLExecDirect();
   while ( rs.SQLFetch() )
   {
      int n = 1;    // order is crucial;
                    // hence, the counter
      string sname     = rs.SQLGetData( n++ );
      string sAddress1 = rs.SQLGetData( n++ );
      string sCity     = rs.SQLGetData( n++ );
      string sState    = rs.SQLGetData( n++ );
      string sZip      = rs.SQLGetData( n++ );

      cout  << left
            << setw(22) << sname
            << sAddress1 << ", "
            << sCity << ", "
            << sState << "  "
            << sZip
            << endl;
   }

Adding a Record

Next, we'll add a record. Note that the overloaded functions, SetColumn() and SetWhere(), will convert strings, doubles, ints, and dates to the correct format for the SQL command.

   try
   {
      CSQLInsert s( "provider" );
      s.SetColumn( "provider", "Smith, Josh" );
      // note that the column name's case is ignored by the
      // ODBC translator; however, the data goes in exactly
      // as you typed it.
      s.SetColumn( "aDDRess1", "123 Anystreet" );
      s.SetColumn( "City", "Spokane" );
      s.SetColumn( "state", "WA" );
      s.SetColumn( "zip", "99204" );
      s.SetColumn( "DOB", true, 12, 13, 1955 );
      s.SetColumn( "Referrals", 0 );
      // note: if you're using a class like COleDateTime, there's
      // a macro in the headers that can be used like this--
      // s.SetColumn( "DOB", SQLBASE_OLEDATETIME(myVar) );
      // otherwise, there's no reference to MFC in the code.
      db.ExecuteSQL( s.GetStatement() );
   }
   catch ( CSQLException* e )
   {
      // in case the inserted record exists
      cout << endl << "Error on insert" << endl;
      cout << e->m_strError << endl;
   }

Performing a Record Update

   try
   {
      CSQLUpdate s( "provider" );
      // where clause necessary for update
      s.SetWhere( "provider", "Smith, Josh" );
      s.SetColumn( "address1", "2903 West Pacific Ave." );
      s.SetColumn( "Referrals=Referrals+1" );
      db.ExecuteSQL( s.GetStatement() );
   }
   catch ( CSQLException* e )
   {
      cout << endl << "Error on update" << endl;
      cout << e->m_strError << endl;
   }

Performing a Deletion

   try
   {
      CSQLDelete s( "provider" );
      // where clause necessary for delete
      s.SetWhere( "provider", "Castanza, George" );
      db.ExecuteSQL( s.GetStatement() );
   }
   catch ( CSQLException* e )
   {
      cout << endl << "Error on delete" << endl;
      cout << e->m_strError << endl;
   }

Running the Sample Program

To run the sample program:

  1. Create a DSN in the ODBC administrator that points to the sample access database, MPHSample.mdb, provided with the project. Call it MPHSample.
  2. Make sure that ImplicitCommitSync is set to 'Yes' in the advanced options for the DSN.
  3. Compile, link, and run the program.

It's pretty easy to get an application up and running with these classes and the overloads keep you out of trouble.

Other Things

I've tested these on Personal Oracle and they work fine. I would imagine that SQL Server would give the same results.

Important: If you decide to close the database connection and reopen it, be sure to close all recordset objects first. Otherwise, you'll get an unknown exception from the ODBC middleware that's pretty hard to track down. You'll see that this is handled in the new demo project. Try removing the catch block (...) and you'll see it even runs differently in debug vs. release mode. Possibly the CSQLDatabase class could use a reference counter and declared as a friend class in CRecordset? Anyway, know this can be an issue and watch out for it.

A comment about the extraction of data. You no doubt noticed that it has to be in sequential order. This is an ODBC feature. I've thought that it would be a good enhancement to use a map file and load the data into it. Then you could extract it using syntax like rs.flds["Name"], rs["Name"] or rs[2] like Jet does it. I'll leave that for you to implement.

I've been using these classes at several sites with 5-6 terminals each pounding on Access databases and I'm getting excellent performance from them.

Permissions

You can freely distribute and use this code in your projects as long as my name is in the revision log. This includes commercial products and projects. Also, feel free to modify them if you like.

Addendum

I'd like to thank everyone for their comments, and especially for the bug fixes on the code. I've included your names in the revision logs.

Downloads

Download demo project - 159 Kb
Download source - 22 Kb

When I update any of my class libraries, I make the code available at this location. Also, if there were any missing source code includes, they can be found here.

Tools:
Add www.codeguru.com to your favorites
Add www.codeguru.com to your browser search box
IE 7 | Firefox 2.0 | Firefox 1.5.x
Receive news via our XML/RSS feed







RATE THIS ARTICLE:   Excellent  Very Good  Average  Below Average  Poor  

(You must be signed in to rank an article. Not a member? Click here to register)

Latest Comments:
Transaction Commit(); Roolback() is not working - Legacy CodeGuru (02/20/2004)
errors - Legacy CodeGuru (09/12/2003)
connecting to access db using odbc - Legacy CodeGuru (06/13/2003)
Need latest version - Legacy CodeGuru (05/23/2003)
Where is Latest version? - Legacy CodeGuru (01/30/2003)

View All Comments
Add a Comment:
Title:
Comment:
Pre-Formatted: Check this if you want the text to display with the formatting as typed (good for source code)



(You must be signed in to comment on an article. Not a member? Click here to register)

internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

Jupitermedia Corporate Info

Legal Notices, Licensing, Reprints, Permissions, Privacy Policy.
Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

Whitepapers and eBooks

Intel Whitepaper: Comparing Two- and Four-Socket Platforms for Server Virtualization
IBM Solutions Brief: Go Green With IBM System xTM And Intel
HP eBook: Simplifying SQL Server Management
IBM Contest: Are You the Next Superstar? Join the "Search for the XML Superstar" Contest to Find Out
Microsoft PDF: Top 10 Reasons to Move to Server Virtualization with Hyper-V
Microsoft PDF: Six Reasons Why Microsoft's Hyper-V Will Overtake Vmware
Microsoft Step-by-Step Guide: Hyper-V and Failover Clustering
Intel PDF: Quad-Core Impacts More Than the Data Center
Intel PDF: Virtualization Delivers Data Center Efficiency
Go Parallel Article: PDC 2008 in Review
Microsoft PDF: Top 11 Reasons to Upgrade to Windows Server 2008
Avaya Article: Communication-Enabled Mashups: Empowering Both Business Owners and IT
Intel Whitepaper: Building a Real-World Model to Assess Virtualization Platforms
  PDF: Intel Centrino Duo Processor Technology with Intel Core2 Duo Processor
Microsoft Article: Build and Run Virtual Machines with Hyper-V Server 2008
Go Parallel Article: Q&A with a TBB Junkie
IBM Whitepaper: Innovative Collaboration to Advance Your Business
Internet.com eBook: Real Life Rails
IBM eBook: The Pros and Cons of Outsourcing
Internet.com eBook: Best Practices for Developing a Web Site
IBM CXO Whitepaper: The 2008 Global CEO Study "The Enterprise of the Future"
Avaya Article: Call Control XML in Action - A CCXML Auto Attendant
IBM CXO Whitepaper: Unlocking the DNA of the Adaptable Workforce--The Global Human Capital Study 2008
Adobe Acrobat Connect Pro: Web Conferencing and eLearning Whitepapers
HP eBook: Guide to Storage Networking
MORE WHITEPAPERS, EBOOKS, AND ARTICLES