VC6.0++ 连接数据库的两种方法
bool CMyDataBase::InitDataBase()
{
//初始化数据库连接
HRESULT hr;
try
{
hr = m_pConnection.CreateInstance("ADODB.Connection");//创建Connection对象
if(SUCCEEDED(hr))
{
hr = m_pConnection->Open("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=DataBase.mdb","","",adModeUnknown);///连接数据库
//hr = m_pConnection->Open("studb","","",adModeUnknown);
}
}
catch(_com_error e)///捕捉异常
{
CString errormessage;
errormessage.Format("连接数据库失败!\r\n错误信息:%s",e.ErrorMessage());
AfxMessageBox(errormessage);///显示错误信息
}
return TRUE;
}
=======================================================================
bool CMyDataBase::InitDataBase()
{
//初始化数据库连接
HRESULT hr;
try
{
//实例化连接对象
hr=m_pConnection.CreateInstance(__uuidof(Connection));
if(SUCCEEDED(hr))
{
//设置连接串属性为UDL文件
m_pConnection->ConnectionString="File Name=my_data1.udl";
//设置等待连接打开的时间为20秒
m_pConnection->ConnectionTimeout=20;
hr=m_pConnection->Open("","","",adConnectUnspecified);
if(FAILED(hr))
{
AfxMessageBox("open fail!");
// return TRUE;
}
}
else
{
AfxMessageBox("createinstance of Connection fail!");
}
}
catch (_com_error e)
{
_bstr_t bstrSource(e.Source());
_bstr_t bstrDescription(e.Description());
AfxMessageBox(bstrSource+bstrDescription);
}
return TRUE;
}
[oledb]
; Everything after this line is an OLE DB initstring
Provider=Microsoft.Jet.OLEDB.4.0;Data Source=DataBase.mdb;Persist Security Info=False
双击运行my_data1.udl,会弹出如下图的窗口: