读书人

请教c++怎么连接SQLServer数据库

发布时间: 2012-02-11 09:51:35 作者: rapoo

请问c++如何连接SQLServer数据库
如题,最好能给个例子!

[解决办法]
char currentexecutepath[1000];
GetCurrentDirectory(1000,currentexecutepath);
AfxEnableControlContainer();
BOOL suc=AfxOleInit(); // 初始化OLE
if (suc==FALSE)
{
::AfxMessageBox( "初始化OLE失败! ");
}
////////////连接数据库//////////////
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=vib.mdb ", " ", " ",adModeUnknown);///连接数据库
CString slink;
slink= "File Name= ";
slink+=currentexecutepath;
slink+= "\\link.udl ";
m_pConnection-> ConnectionString=_bstr_t(slink);//使用Udl文件连接数据库
m_pConnection-> ConnectionTimeout=3;
hr = m_pConnection-> Open( " ", " ", " ",adModeUnknown);
}
}
catch(_com_error e)///捕捉异常
{
CString errormessage;
errormessage.Format( "数据库连接失败!\r\n错误信息:%s\r\n\r\n请先设置数据源 ",e.ErrorMessage());
AfxMessageBox(errormessage);///显示错误信息
m_pConnection=NULL;
bConnectState=false;
}
if (!bConnectState)
{
FILE *pFile=fopen( "link.udl ", "r ");
if (pFile==NULL)
{
pFile=fopen( "link.udl ", "w ");
fclose(pFile);
}
CString s,s1;
s= "link.udl ";//怎么判断是否存在文件link.udl呢。如果没有存在,则新建一个。
ShellExecute(0, _T( "open "), s, 0, currentexecutepath, SW_SHOW|SW_SHOWNORMAL);
exit(0);
}
肯定没错的,我就是这样连mssql的。你给放在app的InitInstance()里面。

读书人网 >C++

热点推荐