C++ ODBC Programming

Status
Not open for further replies.
So I've been finally working on some database programming in C++ and I've come to an impass (which I know I've figured out before, but it was quite a while ago).

I have the basic code to open the connection to the ODBC source, and can even execute the SQL statement. However, iterating through the actual data and collecting it for some basic output seems to be a problem. Either I'm using the wrong thing for this (CRecordset) or I'm not using it right. Here's the program for now, any help or links to help would be appreciated. Till then, MSDN here I come:

code:<HR>
Code:
 <P>#include <iostream.h>
#include <iomanip.h><P>
#include "stdafx.h"<P>
int main( int argc, char* argv[] )
{
  CString sItem1;
  CString sqlQuery;<P>
  CDatabase dbConnection;<P>
  CRecordset dbRecSet ( & dbConnection );<P>
  dbConnection.Open( NULL, FALSE, FALSE, _T( "ODBC;DSN=improbability;UID=sa;PWD=sa" ) );<P>
  sqlQuery = "SELECT indexNumber FROM aspDotNetNews";<P>
  dbConnection.ExecuteSQL( sqlQuery );<P>  dbConnection.Close();<P>
  return 0;<P>}

-Wallace
 

urania

Ars Tribunus Militum
1,784
Here is your problem:
dbConnection.ExecuteSQL( sqlQuery );

It executes the SQL but there is no way to get the returned recordset. I use this for things like delete and update, but not select.

Personally, I open the connection before creating the recordset, but it may not matter.

Go into help and look for CRecordset::Open
What you should be doing instead is:
dbRecSet.Open(,sqlQuery); // with the default options

Then you can do something like:

while (!dbRecSet.IsEOF() && !dbRecSet.IsBOF())
{
dbRecSet.GetFieldValue("FieldName",someVariant);
dbRecSet.MoveNext()
}


Hint: To make it easier:
Go to menu->Insert->New Class....
In the wizard create a new class
Type: MFC Class
Name: CMyRecSet (or whatever)
Base Class: CRecordSet
It will then come up with a dialog "Database Options"
Under ODBC select "improbability" or whatever
select the table

It will then create a class that inherites from CRecordSet
with the columns as 'm_xxxx' variables of the correct type.
The data from the select statement will get mapped into the variables automatically. Much easier than using variants.

then you would be looking at:

CMyRecSet dbRecSet ( & dbConnection );
dbRecSet.Open(,sqlQuery);
while (!dbRecSet.IsEOF() && !dbRecSet.IsBOF())
{
SomeVar = dbRecSet.m_MyVariable;
dbRecSet.MoveNext()
}


Another Hint. You can create a view in SQL Server and then do the above using the view instead of the table.
That way, if you just want a few of the columns or want to use joins, you can still map to variables in the recordset class.

Technically you probably should be using ADO, but I still often use the above RDO code for quick and dirty stuff. I have never cared for the ADO implementation in C++.
 
Status
Not open for further replies.