Introduction
This snippet shows how to connect a Visual Foxpro dbf table and get the field names of the table. It comes from another application in which there should be a database connection interface. And the following is the test function for the interface and it works.
As we know dbf tables are stored independently in some file in the disk, not like a .mdb database whose tables can not be seen at the location the database is via Explorer. So when connecting, the file storing the dbf can be regarded as a database. The function below implements the connection:
void CTttView::OnTest()
{
_ConnectionPtr m_pCon;
_RecordsetPtr m_pRecordset;
AfxOleInit();
m_pCon.CreateInstance(__uuidof(Connection));
HRESULT hr;
try
{
hr=m_pCon->Open("Driver={Microsoft Visual FoxPro Driver}; SourceType=DBF; "
"SourceDB=E:\\c program;", "","",adModeUnknown);
}
catch(_com_error e)
{
AfxMessageBox("Connection failed, check the direction!");
}
m_pRecordset.CreateInstance(__uuidof(Recordset));
m_pRecordset->Open("SELECT * FROM Table1", m_pCon.GetInterfacePtr(), adOpenDynamic, adLockOptimistic, adCmdText);
FieldsPtr pFD=m_pRecordset->GetFields();
_variant_t index;
index.vt = VT_I2;
for(int i=0;i<(int)pFD->GetCount();i++)
{
index.iVal=i;
CString str;
str.Format("Field: %s" ,(LPCSTR)pFD->GetItem(index)->GetName());
MessageBox(str);
}
m_pRecordset->Close();
m_pCon->Close();
}