//stdafx.h #import c:\program files\common files\system\ado\msado15.dll no_namespace rename(eof,adoeof) //主程序初始化函数 bool cado2app::initinstance() { afxenablecontrolcontainer(); afxoleinit();//初始化com库 //--------------------------
//stdafx.h
#import c:\program files\common files\system\ado\msado15.dll no_namespace rename(eof,adoeof)
//主程序初始化函数
bool cado2app::initinstance()
{
afxenablecontrolcontainer();
afxoleinit();//初始化com库
//--------------------------------------------
下面是access的:
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=test.mdb,,,admodeunknown);///连接数据库
///上面一句中连接字串中的provider是针对access2000环境的,对于access97,需要改为:provider=microsoft.jet.oledb.3.51; }
}
}
catch(_com_error e)///捕捉异常
{
cstring errormessage;
errormessage.format(连接数据库失败!\r\n错误信息:%s,e.errormessage());
afxmessagebox(errormessage);///显示错误信息
return false;
}
下面是连接sql server的
cstring strsql;
hresult hr;
try
{
hr=m_pconnection.createinstance(__uuidof(connection));
m_pconnection->cursorlocation=aduseclient;
strsql=provider=sqloledb.1;integrated security=sspi;persist security info=false;initial catalog=test;data source=yjm;
if(succeeded(hr))
{
hr=m_pconnection->open(_bstr_t(strsql),,,-1);
}
}
catch(_com_error e)///捕捉异常
{
cstring errormessage;
errormessage.format(连接数据库失败!\r\n错误信息:%s,e.errormessage());
afxmessagebox(errormessage);///显示错误信息
return false;
}
//afxmessagebox(connected~~);
其中:
----- ado连接sql server的数据库连接字符串模板----------
身份验证模式为:sql server和windows
provider=sqloledb.1;persist security info=true;user id=用户名;password=密码;initial catalog=数据库名;data source=sql服务器名
身份验证模式为:仅windows
provider=sqloledb.1;integrated security=sspi;persist security info=false;initial catalog=数据库名;data source=sql服务器名
注:表名有中文,sqlserver中select的时候要加[]