4,011
社区成员
发帖
与我相关
我的任务
分享
注:*****代表你所建立的工程名称
先在stdafx.h中导入#import "c:\program files\common files\system\ado\msado15.dll" no_namespace rename("EOF","adoEOF")
加入头文件
#include "icrsint.h"
#include "adoid.h"
然后进行下面的书写,必须要初始化COM 即::CoInitialize(NULL);
还要加入成员变量
_RecordsetPtr pRec;
_ConnectionPtr pCon;
BOOL C*****App::InitInstance()
{
if (!AfxSocketInit())
{
AfxMessageBox(IDP_SOCKETS_INIT_FAILED);
return FALSE;
}
AfxEnableControlContainer();
CString str;
::CoInitialize(NULL); //初始化com 必须为NULL
str.Format("Provider=sqloledb;Network Library=DBMSSOCN;Initial Catalog=Test;User ID=sa;Password=1234;Data Source=192.168.0.20,1433");
pCon.CreateInstance(__uuidof(Connection));
try{
pCon->Open(_bstr_t(str),"","",adModeUnknown);
}
catch(_com_error e)
{
MessageBox(NULL,"连接数据库失败!","警告",MB_OK|MB_ICONHAND);
return FALSE;
}
}
在C****App中添加执行sql语句的方法
bool C*****App::OpenSQL(CString &strRec)
{
pRec.CreateInstance(__uuidof(Recordset));
if ( pRec->State )// 如果记录集打开的话,把它关了
pRec->Close();
try{// 正常的SQL语句
pRec->Open(_variant_t(strRec),pCon.GetInterfacePtr(),adOpenDynamic,adLockOptimistic,adCmdText);
return true;
}
catch(_com_error e)
{
MessageBox(NULL,"连接表出错!","警告",MB_OK|MB_ICONHAND);
return false;
}
}
在退出的时候关闭数据库连接
int C****App::ExitInstance()
{
try
{ // 关闭数据库
if ( pCon->State )
pCon->Close();
pCon.Release();
}
catch(_com_error e)
{
}
::CoUninitialize();
return CWinApp::ExitInstance();
}
strConnStr.Format("Driver={SQL Server};Server=%s;Database=%s;Uid=%s;Pwd=%s;", strDBServer, strDBName, strDBUser, strDBPassword);