原理就是通過枚舉數據庫中的表的類型,用戶建立的表的類型一般是TBALE。所以通過判斷當前數據庫中表的類型,就可以獲取表的名稱了。
初始化部分
在stdafx.h中添加:
#include <icrsint.h>
#include <basetsd.h>
#include <ole2.h>
#import "c:Program FilesCommon FilesSystemADOmsado15.dll"
no_namespace rename("EOF", "EndOfFile")
在主對話框的頭文件中,映射一個:
CListBox m_strList;
實現部分說明:
在構造函數中添加:
::CoInitialize(NULL); //初始化Com庫
實現代碼:
//枚舉數據表的名稱處理
void OpenSchemaX(TCHAR *TableName)
{
HRESULT hr = S_OK;
::CoInitialize(NULL); //初始化Com
IADORecordBinding *picRs = NULL;
_RecordsetPtr pRstSchema("ADODB.Recordset");
_ConnectionPtr pConnection("ADODB.Connection" );
pConnection->ConnectionString = TableName;
pConnection->Provider = "Microsoft.Jet.OLEDB.4.0";
try
{
pConnection->Open(pConnection->ConnectionString, "", "", adModeUnknown);
pRstSchema->QueryInterface(
__uuidof(IADORecordBinding), (LPVOID*)&picRs);
pRstSchema = pConnection->OpenSchema(adSchemaTables);//枚舉表的名稱處理
while(!(pRstSchema->EndOfFile))
{
CString strTableType;
_bstr_t table_name = pRstSchema->Fields->
GetItem("TABLE_NAME")->Value;//獲取表的名稱
_bstr_t table_type = pRstSchema->Fields->
GetItem("TABLE_TYPE")->Value;//獲取表的類型
strTableType.Format("%s",(LPCSTR) table_type);
if(!lstrcmp(strTableType,_T("TABLE")))
{
m_strList.AddString((LPCSTR) table_name);//添加表的名稱
}
pRstSchema->MoveNext();
}
// Clean up objects before exit.
pRstSchema->Close();
pConnection->Close();
}
catch (_com_error &e)
{
// Notify the user of errors if any.
// Pass a connection pointer accessed from the Connection.
PrintProviderError(pConnection);
PrintComError(e);
}
CoUninitialize();
}