
Help: MFC Database Sample code (non-GUI)
Hi Chad,
The following demo does what you want, and accepts command-line arguments
for the database name, and the table to list. Note that it doesn't use the
ODBC DSN (doing so would simply require that we change the Db.Open function
to accept 4 parameters, the last of which is the DSN info). The reason for
this, is that I tried to write the program in 10 lines of code (I'm not
counting the #include's and the braces).
Also, note that the parameters to Rs.Open() could be changed to be a 'Select
* from ???' SQL statement. I didn't do that because I wanted the command
line arguments, and again, I wanted to keep it <= 10 lines of code.
Finally, I'm only outputting the first field of the table. Again, this was
just to keep the line count down. You can iterate through the field count
to get all the values if you like. And, there's no error handling, so if a
table or database can't be opened, then it does a crash and burn.
The information for doing all this was from the online help, specifically
the article on Dynamic Binding of SQL columns in a CDaoRecordset class.
#include <iostream.h>
#include <afxdao.h>
void main( int argc, char *argv[])
{
CDaoDatabase Db;
Db.Open( argc>1?argv[1]:"c:\\work\\school\\c3\\prnt\\nwind.mdb" );
CDaoRecordset Rs(&Db);
Rs.Open( dbOpenTable, argc>2?argv[2]:"customers" );
COleVariant Val;
for( ; !Rs.IsEOF() ; Rs.MoveNext() )
{
Rs.GetFieldValue( 0, Val );
Val.ChangeType( VT_BSTR );
cout << (LPCSTR)Val.pbstrVal << endl;
}
AfxDaoTerm();
Quote:
}
> Hello:
> I need to implement a "data accessor" object in C++. This object should
> be able to connect to a simple MS Access database table. I am not using
> the app wizard since the object is non-GUI based.
> The sample code should use the MFC database classes to open a DSN,
> perform a SQL statement and then process the result set. I simply want
> to print the information out the console using cout.
> I just finished writing a data accessor object in Java. I was able to
> quickly find 10 lines of sample code to accomplish this in Java.
> However, I'm really having a hard time to find the comparable thing in
> Visual C++. AppWizard adds all of the GUI content that I don't need.
> Maybe I can't do a stand-alone (non-GUI) database program w/ Visual
> C++...
> Can someone please point me in the right direction for sample source
> code? Any help would be much appreciated. Cheers!
> --
> -----------------------------------------------
> Chad (shod) Darby | J9 Consulting
> -----------------------------------------------
---------------------------------------------------
www.openroad.org - A Free website for beginners and
students of programming.
Remove HAHA from email address to reply
"In computer programming and motorcycle racing,
Crashing Sucks!"
-Me