4,011
社区成员
发帖
与我相关
我的任务
分享
//数据库连接、读记录及断开操作
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "ADOConn.h"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
ADOConn::ADOConn()
{
}
ADOConn::~ADOConn()
{
}
//初始化——连接数据库
BOOL ADOConn::ConnectSQL(CString Server,CString uid,CString pwd)
{
// 初始化OLE/COM库环境
::CoInitialize(NULL);
try
{
// 创建Connection对象
if(m_pConnection==NULL)
m_pConnection.CreateInstance("ADODB.Connection");
// 设置连接字符串,必须是BSTR型或者_bstr_t类型
//;Integrated Security=SSPI;下面字符串加上这个则表示使用windows 帐户连接
_bstr_t strConnect =_T("Provider=SQLOLEDB.1;Persist Security Info=False;\
Initial Catalog=Elector_DB;Data Source=")+Server+";uid="+uid+";pwd="+pwd+";";
m_pConnection->Open(strConnect,"","",adModeUnknown);
}
// 捕捉异常
catch(_com_error e)
{
//MessageBox(_T("数据库连接失败,请开启数据库服务!"));
// PostQuitMessage(0);
AfxMessageBox(e.Description());
return false;
}
return true;
}
// 执行查询
_RecordsetPtr& ADOConn::GetRecordSet(_bstr_t bstrSQL)
{
try
{
// 连接数据库,如果Connection对象为空,则重新连接数据库
// if(m_pConnection==NULL)
// OnInitADOConn();
// 创建记录集对象
m_pRecordset.CreateInstance(__uuidof(Recordset));
// 取得表中的记录
// m_pRecordset->Open(bstrSQL,m_pConnection.GetInterfacePtr(),adOpenDynamic,adLockOptimistic,adCmdText);
m_pRecordset->Open(bstrSQL,m_pConnection.GetInterfacePtr(),adOpenStatic,adLockOptimistic,adCmdText);
}
// 捕捉异常
catch(_com_error e)
{
// 显示错误信息
AfxMessageBox(e.Description());
}
// 返回记录集
return m_pRecordset;
}
// 执行查询
_RecordsetPtr& ADOConn::GetDynamicRecordSet(_bstr_t bstrSQL) //取得动态光标查询记录集,新的修改可以立刻反应出来
{
try
{
// 连接数据库,如果Connection对象为空,则重新连接数据库
// if(m_pConnection==NULL)
// OnInitADOConn();
// 创建记录集对象
m_pRecordset.CreateInstance(__uuidof(Recordset));
// 取得表中的记录
m_pRecordset->Open(bstrSQL,m_pConnection.GetInterfacePtr(),adOpenDynamic,adLockOptimistic,adCmdText);
}
// 捕捉异常
catch(_com_error e)
{
// 显示错误信息
AfxMessageBox(e.Description());
}
// 返回记录集
return m_pRecordset;
}
// 执行SQL语句,Insert Update _variant_t
BOOL ADOConn::ExecuteSQL(_bstr_t bstrSQL)
{
try
{
// 是否已经连接数据库
if(m_pConnection==NULL)
return false;
// Connection对象的Execute方法:(_bstr_t CommandText,
// VARIANT * RecordsAffected, long Options )
// 其中CommandText是命令字串,通常是SQL命令。
// 参数RecordsAffected是操作完成后所影响的行数,
// 参数Options表示CommandText的类型:adCmdText-文本命令;adCmdTable-表名
// adCmdProc-存储过程;adCmdUnknown-未知
m_pConnection->Execute(bstrSQL,NULL,adCmdText);
return true;
}
catch(_com_error e)
{
AfxMessageBox(_T("数据库SQL语句执行失败!"));
// PostQuitMessage(0);
//MessageBox(e.Description());
return false;
}
}
void ADOConn::ExitConnect()
{
// 关闭记录集和连接
if(m_pRecordset!=NULL)
m_pRecordset->Close();
m_pConnection->Close();
// 释放环境
::CoUninitialize();
}
void ADOConn::Close()
{
m_pConnection->Cancel();
ExitConnect();
m_pConnection=NULL;
}