MFC通过ADO连接SQL SERVER数据库

以一个MFC的Dialog应用程序为例。

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函数中加上:

1AfxOleInit();

3.建立连接的函数,可以单独放在SQLHelper类中(专门处理数据库操作的函数)。

01//打开连接
02_ConnectionPtr SqlHelper::getConnection()
03{
04    _ConnectionPtr m_pConnection;
05    //连接字符串
06    try
07    {
08        m_pConnection.CreateInstance("ADODB.Connection");
09        HRESULT rs;
10        CString connectionStr="Driver={SQL Server};Server=(local);Database=db_superMarket;UID=sa;PWD=***";
11        rs=m_pConnection->Open((_bstr_t)connectionStr,"","",adModeUnknown);
12        if(rs)
13        {
14            AfxMessageBox("连接失败!");
15        }
16    }
17    catch(_com_error e)
18    {
19        AfxMessageBox(e.ErrorMessage());
20    }
21    return m_pConnection;
22}

4.关闭连接的函数:

1//关闭链接
2void SqlHelper::closeConnection(_ConnectionPtr conn)
3{
4    if(conn!=NULL)
5        conn->Close();
6}

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值