在 C++ 中使用 ADO 连接到 Visual FoxPro (dbf) 表






1.35/5 (6投票s)
这是一个简单的示例,展示如何使用 ADO 连接 dbf 表以获取数据库连接。
引言
这段代码片段展示了如何连接 Visual Foxpro 的 *dbf* 表并获取表的字段名称。它来自另一个应用程序,该应用程序应该具有数据库连接接口。以下是该接口的测试函数,并且可以正常工作。
正如我们所知,*dbf* 表独立存储在磁盘上的某个文件中,不像 *mdb* 数据库,其表无法通过资源管理器在数据库所在位置看到。因此,在连接时,存储 *dbf* 文件的位置可以被视为数据库。下面的函数实现了连接。
void CTttView::OnTest()
{
_ConnectionPtr m_pCon;
_RecordsetPtr m_pRecordset;
AfxOleInit();
m_pCon.CreateInstance(__uuidof(Connection));
HRESULT hr;
try
{
//The SourceDB should be a proper directory
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", //Table1 is a dbf table name
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();
}