VC++中如何使用ADO连接局域网服务器中access数据库?急!

hr = m_pConnection->Open( "Provider=SQLOLEDB.1;Password=密码;Persist Security Info=True;User ID=用户名;Initial Catalog=数据库名;Data Source=127.0.0.1(本机)", "", "", adConnectUnspecified); 不大明白 这好像是访问SQL数据库的代码啊?最上面的代码只能访问本地access数据库

这是连接access数据库的代码:try
{
hr=m_pCon.CreateInstance("ADODB.Connection");
if(SUCCEEDED(hr))
{
m_pCon->ConnectionTimeout=3;//异常超时时间

hr=m_pCon->Open("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=canyin.mdb","","",adModeUnknown); //设置数据库名,用户名,密码

}
}

ADO访问数据库的基本步骤:

(1)、引入ADO类 ,加到stdafx.h中#endif // _AFX_NO_AFXCMN_SUPPORT后面

#import "c:\program files\common files\system\ado\msado15.dll" \
no_namespace \
rename ("EOF", "adoEOF")

(2)、初始化COM (放在对话框初始化函数里面或者CXXXApp::InitInstance()中)

在MFC中可以用AfxOleInit();非MFC环境中用:
CoInitialize(NULL);
CoUnInitialize();

(3)、包含后就可以用3个智能指针了:_ConnectionPtr、_RecordsetPtr和_CommandPtr

(4)、连接数据库
HRESULT hr;
try
{
hr = m_pConnection.CreateInstance("ADODB.Connection");///创建Connection对象
if(SUCCEEDED(hr))
{
m_pConnection->ConnectionTimeout = 0;
hr = m_pConnection->Open( "Provider=SQLOLEDB.1;Password=密码;Persist Security Info=True;User ID=用户名;Initial Catalog=数据库名;Data Source=127.0.0.1(本机)", "", "", adConnectUnspecified);

m_pCommand.CreateInstance(__uuidof(Command));
m_pCommand->CommandTimeout = 5;
m_pCommand->ActiveConnection = m_pConnection;
}
}
catch(_com_error e)///捕捉异常
{
CString errormessage;
errormessage.Format("连接数据库失败!\r\n错误信息:%s,%s",e.ErrorMessage(),e.Description());
AfxMessageBox(errormessage);///显示错误信息
}

(5)、打开记录集
首先创建一个_RecordsetPtr实例,然后调用Open()得到一条SQL语句的执行结果
_RecordsetPtr m_pRecordset;
m_pRecordset.CreateInstance(__uuidof(Recordset));

// 在ADO操作中建议语句中要常用try...catch()来捕获错误信息,
// 因为它有时会经常出现一些意想不到的错误
try
{
m_pRecordset->Open("SELECT * FROM DemoTable",// 查询DemoTable表中所有字段
m_pConnection.GetInterfacePtr(), // 获取库接库的IDispatch指针
adOpenDynamic,
adLockOptimistic,
adCmdText);
}
catch(_com_error *e)
{
AfxMessageBox(e->ErrorMessage());
}

……
温馨提示:答案为网友推荐,仅供参考
相似回答