SQL server配置按我的另一篇文章即可搞定。环境配置好后,按又下方法即可连接到任一数据库,对其进行操作。
主要步骤为:
1. 在stdafx.h头文件末尾中加入
#import "C:\Program Files\Common Files\System\ado\msado15.dll" named_guids rename("EOF","adoEOF")
#pragma warning(default:4146)
using namespace ADODB;
//如果你的文件路径不同,做相应改变即可,但每个有VS环境的人都有msado15.dll这个文件。
//named_guids rename()语句改变数据集的“EOF”名称为别名“adoEOF”,又便在程序中使用,你也可又不用改变。
2、使用定义_ConnectionPtr定义数据库连接句柄
3、使用定义_ConnectionPtr.reateInstance()方法初始化
4、使用_RecordsetPtr,或_commandPtr连接_connectionPtr定义的连接,然后即可访问数据
代码如下:
CString strConnect="Provider=SQLOLEDB;Server=.\\xxxxxxxxx or (xxx.xxx.xxx.xxx, port);Database=xxxxx;uid=xxxxxx;pwd=xxxxxxxx"
//如果连接ACCSS DATABASE 则
CString strConnect="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=xxxxx;Persist Security Info=False"
/
_ConectionPtr MyConnect;
HRESULT hr=MyConnect.CreateInstance(_uuidof(Connection));
if(FAILED(hr))
{
return FALSE;
}
_bstr_t strConnect=IniString;//
try
{
MyConnect->CursorLocation=adUseServer ;
MyConnect->Open(strConnect,"","",NULL);
}
catch (_com_error &e)
{
::MessageBox(NULL,e.Description(),L"Warning",MB_OK | MB_ICONWARNING);
return FALSE;
}
_RecordsetPtr m_pRecordset;
_CommandPtr m_pCommand;
// if(FAILED(m_pRecordset.CreateInstance( __uuidof( Recordset ))))
// {
//
// ::MessageBox(NULL,L"Can not CreateInstance of Record",L"Warning",MB_OK | MB_ICONWARNING);
// return FALSE;
// }
if(FAILED(m_pCommand.CreateInstance( __uuidof( Command ))))
{
::MessageBox(NULL,L"Can not Open the Recordset",L"Warning",MB_OK | MB_ICONWARNING);
return NULL;
}
m_pCommand->put_ActiveConnection(_variant_t((IDispatch *)MyConnect));
m_pCommand->CommandText =SQLstring;
//m_pCommand->CommandText="INSERT INTO OPENDATASOURCE('Microsoft.Jet.OLEDB.4.0','Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c://XXX.mdb;Persist Security Info=False')...TB_FILM SELECT * FROM db1";
try
{
m_pRecordset=m_pCommand->Execute(NULL,NULL,adCmdText);
}
catch (_com_error &e)
{
::MessageBox(NULL,e.Description(),L"Warning",MB_OK | MB_ICONWARNING);
}