以一个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函数中加上:
1 | AfxOleInit(); |
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 | //关闭链接 |
2 | void 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;
}