VC訪問Sybase數據庫,下面給出通過ADO連接ASE的方法:
1.VC程序中引進ADO
#import "C:\Program Files\Common Files\System\ado\msado15.dll" no_namespace rename("EOF","rSEOF")
2.初始化COM環境,函數需成對出現。
CoInitialize(NULL); CoUninitialize();
3.創建連接等對象。
_ConnectionPtr pConn(__uuidof(Connection));
_RecordsetPtr pRst(__uuidof(Recordset));
_CommandPtr pCmd(__uuidof(Command));
4. 連接字符串。這是ASE數據的連接字符串,要連接上需在ASE 安裝目錄下的 \\Sybase\OLEDB-2_1\sydaadm.exe 文件中配置並確保連接成功。
pConn->ConnectionString="Provider=Sybase.ASEOLEDBProvider.2;PassWord=xxx;User ID=sa;Data Source=STS129;Persist Security Info=True";
5.打開連接。
pConn->Open("","","",adConnectUnspecifIEd); //Open()前三個參數在ConnectionString已給出.
6、返回結果集。
pRst=pConn->Execute("select * from Buyer",NULL,adCmdText);
pRst->Open("select * from Buyer",_variant_t((IDispatch*)pConn),
adOpenDynamic,adLockOptimistic,adCmdText);
//pCmd->put_ActiveConnection(_variant_t((IDispatch*)pConn));
//pCmd->CommandText="select * from Buyer";
//pRst=pCmd->Execute(NULL,NULL,adCmdText);
while(!pRst->rSEOF)
{
((CListBox*)GetDlgItem(IDC_LIST1))->AddString(
(_bstr_t)pRst->GetCollect("Buyer"));
pRst->MoveNext();
}
7、釋放。
pRst->Close();
pConn->Close();
pCmd.Release();
pRst.Release();
pConn.Release();
CoUninitialize();
------整個過程實現可以參看如下代碼-----------------------------------------
void CAdoDlg::OnBtnQuery()
{
// TODO: Add your control notification handler code here
CoInitialize(NULL);
_ConnectionPtr pConn(__uuidof(Connection));
_RecordsetPtr pRst(__uuidof(Recordset));
_CommandPtr pCmd(__uuidof(Command));
pConn->ConnectionString="Provider=Sybase.ASEOLEDBProvider.2;PassWord=S129XYJ;User ID=sa;Data Source=STS129;Persist Security Info=True";
pConn->Open("","","",adConnectUnspecifIEd);
pRst=pConn->Execute("select * from Buyer",NULL,adCmdText);
pRst->Open("select * from Buyer",_variant_t((IDispatch*)pConn),
adOpenDynamic,adLockOptimistic,adCmdText);
// pCmd->put_ActiveConnection(_variant_t((IDispatch*)pConn));
// pCmd->CommandText="select * from Buyer";
// pRst=pCmd->Execute(NULL,NULL,adCmdText);
while(!pRst->rSEOF)
{
((CListBox*)GetDlgItem(IDC_LIST1))->AddString((_bstr_t)pRst->GetCollect("Buyer"));
// ((CListBox*)GetDlgItem(IDC_LIST2))->AddString((_bstr_t)pRst->GetCollect ("Description"));
((CListBox*)GetDlgItem(IDC_LIST2))->AddString((_bstr_t)pRst->GetCollect(_variant_t((long)1))); //_variant_t((long)1 表示第二個字段
pRst->MoveNext();
}
pRst->Close();
pConn->Close();
pCmd.Release();
pRst.Release();
pConn.Release();
CoUninitialize();
}