Tag Archives: wx

wxWidgets and ODBC…

Since wxWidgets > 2.8 has dropped wxODBC, I decided to learn how to use sql.h on my own.  I made a simple program to retrieve and print data in C for the command line and everything worked well.  Unfortunately, when I placed this code in my wxWidgets GUI program, it failed.  This was due to wx being unicode, so I had a whole world of learning on how to make sql.h talk with wx.  I’ve outlined the steps to make this work:

With ODBC, sql.h can work with unicode, the functions are the same, but different variables are sent.  WX defines as Unicode (as it’s usually compiled) and ODBC will map the function to the unicode variant.  For example, in a C++ program with #define UNICODE 1, such as WX, SQLDriverConnect will map to SQLDriverConnectW, the unicode variant.  The other option is SQLDriverConnectA which will allow ANSI variables.  Most of the functions you’ll need have an ‘A Variant’, which is what I’ll refer to the functions ending in A.

To Send Data:

  1. Cast your variable as a SQLWCHAR pointer.
  2. Set a string to that pointer, type cast the string too.
  3. Use the functions of ODBC that end with an A.
  4. Send that function a variable type cast as (SQLCHAR*).
SQLWCHAR *connStr;
connStr = (SQLWCHAR*)"DSN=testDB;";
SQLDriverConnectA(dbc, NULL, (SQLCHAR*)connStr, SQL_NTS,
    (SQLCHAR*)outstr, sizeof(outstr), &outstrlen,
     SQL_DRIVER_COMPLETE);

To Return Data:

  1. Do the same steps.
SQLWCHAR colName[256];
SQLDescribeColA(hstmt, i+1, (SQLCHAR*)colName, 255, &colNameLen,
      &dataType, &colSize, &numDecimalDigits, &allowsNullValues);

Convert SQLWCHAR to wxString:

  1. Use wxString’s PrintF() function and interpret the variable with a capital S.
SQLWCHAR colName[256];
wxString test;
test.PrintF(_("Column Name: %S"),colName);

Convert wxString to SQLWCHAR:

  1. Declare your buffer variable as SQLCHAR array.
  2. Cycle through each char in wxString and assign to your SQLCHAR array.
  3. Add a null value on the end (so SQL_NTS knows to stop!)
  4. Typecast the variable as a pointer in send.
wxString send = wxT("SELECT * FROM master");
SQLCHAR sqlTest[1024];
unsigned int j;
for(j=0;j<send.Len();j++) {
sqlTest[j] = send[j];
}
sqlTest[send.Len()] = _T('\0');

SQLPrepareA(hstmt, (SQLCHAR*)sqlTest, SQL_NTS);