Introduction
This demo project shows you easily how you can access a dBase file with ODBC.
How to create a database DSN
Start -> Administrative Tools -> Data Sources (ODBC) -> User-DSN-> Add
I work with a ODBC - Driver for dBase 5.0. At
microsoft.com you can download the ODBC-Jet Driver.
You have to create a DSN with the driver Microsoft dBase Driver (*.dbf), with the name test_dbase
and with the right path to the file. Without creating the DSN, the application won't find the dBase file!
Using the code
This code is one part of the project, which is the most interesting !
#include "stdafx.h"
#include "afxdb.h"
CRecordset rec;
CDatabase db;
char sz_statement [2048] = "";
char sz_connect [250] = "";
CString s_name;
CString s_age;
sprintf(sz_connect,"ODBC;DSN=test_dbase;");
try
{
db.Open(sz_connect);
}
catch(CDBException *e)
{
e->Delete ();
}
rec.m_pDatabase = &db;
printf(" Name | Age\n");
printf("------------------\n");
strcpy(sz_statement,"SELECT * FROM name_list");
try
{
rec.Open(CRecordset::forwardOnly, sz_statement);
while(!rec.IsEOF())
{
rec.GetFieldValue("NAME", s_name);
printf("%-10s | ",s_name);
rec.GetFieldValue("AGE", s_age);
printf("%-5s\n",s_age);
rec.MoveNext();
}
rec.Close();
}
catch (CDBException *e)
{
e->Delete ();
}
db.Close();
The string: "ODBC;DSN=test_dbase;"
is the connection string for the database.
db.Open(sz_connect);
Call this member function to initialize a newly constructed CDatabase
object. Your database object must be initialized before you can use it to construct a recordset
object.
rec.m_pDatabase = &db;
Contains a pointer to the CDatabase
object through which the recordset
is connected to a data source.
rec.Open(CRecordset::forwardOnly, sz_statement);
You must call this member function to run the query defined by the recordset
. Before calling Open
, you must construct the recordset
object.
rec.GetFieldValue("NAME", s_name);
Call this member function to retrieve field data in the current record. You can look up a field either by name or by index. You can store the field value in a CString
object.
rec.MoveNext();
Call this member function to make the first record in the next rowset
the current record. If you have not implemented bulk row fetching, your recordset has a rowset size of 1, so MoveNext
simply moves to the next record.
rec.Close();
Call this member function to close the recordset
.
db.Close();
Call this member function if you want to disconnect from a data
History
- 24.01.2003 - First Version is finished...
- 15.05.2003 - Second Version => changed some text and changed code
- 02.07.2003 - Major rewrite