用ADO通過DSN動態連接數據庫時:(MFC基於對話框 )
//stdafx.h
#import "c:\program files\common files\system\ado\msado15.dll" no_namespace rename("EOF","adoEOF")
//主程序初始化函數
BOOL CADO2App::InitInstance()
{
AfxEnableControlContainer();
AfxOleInit();//初始化COM庫
首先添加一個對話框,然後調用該對話框初始化的時候讀取DSN名字
//把DSN名字顯示到列表框中 列表框ID :IDC_DSN_LIST
((CListBox*)GetDlgItem(IDC_DSN_LIST))->ResetContent();
HKEY hKey;
RegOpenKeyEx(HKEY_CURRENT_USER,"Software\\ODBC\\ODBC.INI\\ODBC Data Sources",0,KEY_READ,&hKey);
DWord dwKeyCount;
DWord dwMaxKeyNameLength;
RegQueryInfoKey(hKey,NULL,NULL,NULL,NULL,NULL,NULL,&dwKeyCount,&dwMaxKeyNameLength,NULL,NULL,NULL);
char* szKeyName = new char[dwMaxKeyNameLength+1];
DWord dwKeyName;
for (long index=0;index<(long)dwKeyCount;index++)
{
RegEnumValue(hKey,index,szKeyName,&dwKeyName,NULL,NULL,NULL,NULL);
CString DSNName;
DSNName.Format("%s",szKeyName);
((CListBox*)GetDlgItem(IDC_DSN_LIST))->AddString(DSNName);
}
delete szKeyName;
RegCloseKey(hKey);
然後單擊選擇例表框內容,然後把選種的內容記錄成CString m_strDSNName
最後通過ado連接來實現動態連接到數據源
HRESULT hr;
try
{
hr = m_pConnection.CreateInstance("ADODB.Connection");///創建Connection對象
if(SUCCEEDED(hr))
{
hr = m_pConnection->Open("DSN="+"_bstr_t(m_strDSNName),"","",0);