MFC通过ADO连接MS SQLSERVER数据库
时间:2011-01-29 来源:风清月明
1.首先是引入msado15.dll。
在StdAfx.h中加入:
#import "C:\Program Files\Common Files\System\ado\msado15.dll" \
no_namespace rename("EOF","adoEOF")
2.初始化COM。
在SuperManDlg.cpp文件的OnInitDialog函数中加上:
AfxOleInit();
3.建立连接的函数,可以单独放在SQLHelper类中(专门处理数据库操作的函数)。
//打开连接
_ConnectionPtr SqlHelper::getConnection()
{
_ConnectionPtr m_pConnection;
//连接字符串
try
{
m_pConnection.CreateInstance("ADODB.Connection");
HRESULT rs;
CString connectionStr="Driver={SQL Server};Server=(local);Database=db_superMarket;UID=sa;PWD=***";
rs=m_pConnection->Open((_bstr_t)connectionStr,"","",adModeUnknown);
if(rs)
{
AfxMessageBox("连接失败!");
}
}
catch(_com_error e)
{
AfxMessageBox(e.ErrorMessage());
}
return m_pConnection;
}
4.关闭连接的函数:
//关闭链接
void SqlHelper::closeConnection(_ConnectionPtr conn)
{
if(conn!=NULL)
conn->Close();
}
5.进行查询的函数
代码
//获得记录数
int SqlHelper::GetRecord(CString sql)
{
int num=0;
_ConnectionPtr m_pConnection=getConnection();
_RecordsetPtr m_pRecordSet=NULL;
m_pRecordSet.CreateInstance(__uuidof(Recordset));
try
{
m_pRecordSet->Open((_bstr_t)sql,m_pConnection.GetInterfacePtr(),adOpenDynamic,adLockOptimistic,adCmdText);
}
catch(_com_error e)
{
AfxMessageBox(e.Description());
}
if(m_pRecordSet!=NULL)
{
while(!(m_pRecordSet->adoEOF))
{
num++;
m_pRecordSet->MoveNext();
}
}
if(m_pRecordSet!=NULL)
{
m_pRecordSet->Close();
}
closeConnection(m_pConnection);
return num;
}
相关阅读 更多 +
排行榜 更多 +
代码










