mfc使用ado连接数据库
1.设置数据源
打开控制面板--->系统和安全--->管理工具--->ODBC Data Sources(32 bit)
这里需要注意的是,vc6.0是32位的,因此这里的数据源也必须是32位的,否则是连接不上的,
这里我使用的是ACCESS数据库,数据源的配置如下:
2.创建包含数据库的MFC对话框(其它也可以)工程,新建ADOConn类
在工程中我们需要新建一个普通类ADOConn
然后在ADOConn类头文件中加入以下导入声明和变量、函数声明:
ADOConn.h---------------------------------------------------------------------------------
#import "c:\Program Files\Common Files\System\ado\msado15.dll" no_namespace rename("EOF","adoEOF")//引入ADO库文件
public:
_ConnectionPtr m_pConnection;//连接对象指针
_RecordsetPtr m_pRecordset;//记录集对象指针
_CommandPtr m_pCommand;//命令对象指针
ADOConn();
virtual ~ADOConn();
BOOL OnInitADOConn(CString Connstr);//初始化连接数据库
BOOL ExecuteSQL(CString strSQL);//执行SQL语句
BOOL ExecuteProc(CString ProcName);//执行存储过程
BOOL GetCollect(CString FieldName,CString & strDest);//获得某个字段的值
BOOL GetRecordSet(CString strSQL);//获得记录集
int GetRecordCount();//获得记录数
//判断表TableName中是否存在字段KeyName的值为KeyValue的记录
BOOL RecordExist(CString TableName,CString KeyName,CString KeyValue);
BOOL MoveFirst();//移动到第一条记录
BOOL MoveNext();//移动到下一条记录
BOOL Close();//关闭记录集
BOOL CloseADOConnection();//关闭连接
void dump_com_error(_com_error &e);//错误详细信息
ADOConn.h---------------------------------------------------------------------------------
然后在ADOConn类源文件中加入函数实现:
ADOConn.cpp---------------------------------------------------------------------------------
ADOConn::ADOConn()//构造函数
{
}
ADOConn::~ADOConn()//析构函数
{
}
BOOL ADOConn::OnInitADOConn(CString ConnStr)//初始化连接数据库
{
try{
m_pRecordset.CreateInstance("ADODB.Recordest");
m_pCommand.CreateInstance("ADODB.Command");
m_pConnection.CreateInstance("ADODB.Connection");
_bstr_t strConnect=(_bstr_t)ConnStr;
m_pConnection->Open((_bstr_t)strConnect,"","",adModeUnknown);
AfxMessageBox("数据库连接成功");
return true;
}catch(_com_error e){
AfxMessageBox("数据库连接失败");
return false;
}
}
BOOL ADOConn::ExecuteSQL(CString strSQL)//执行SQL语句
{
try{
m_pConnection->BeginTrans();
m_pConnection->Execute(_bstr_t(strSQL),NULL,adCmdText);
m_pConnection->CommitTrans();
return true;
}catch(_com_error e)
{
m_pConnection->RollbackTrans();
AfxMessageBox("执行SQL语句失败");
return false;
}
}
BOOL ADOConn::ExecuteProc(CString ProcName)//执行存储过程
{
try{
m_pCommand->ActiveConnection=m_pConnection;
m_pCommand->CommandText=_bstr_t(ProcName);
m_pCommand->Execute(NULL,NULL,adCmdStoredProc);
return true;
}catch(_com_error e){
AfxMessageBox("执行存储过程失败");
return false;
}
}
BOOL ADOConn::GetCollect(CString FieldName,CString & strDest)//获得某个字段的值
{
VARIANT vt;
try{
vt=m_pRecordset->GetCollect(_variant_t(FieldName));
switch(vt.vt){
case VT_BSTR:
strDest=(LPCSTR)_bstr_t(vt);
break;
case VT_DECIMAL:
strDest.Format("%d",vt.intVal);
break;
case VT_DATE:
{
DATE dt=vt.date;
COleDateTime da=COleDateTime(dt);
strDest.Format("%d-%d-%d %d: %d: %d",da.GetYear(),da.GetMonth(),da.GetDay(),da.GetHour(),da.GetMinute(),da.GetSecond());
break;
}
case VT_NULL:
strDest="";
break;
}
return true;
}catch(_com_error e){
AfxMessageBox(e.ErrorMessage());
return false;
}
return true;
}
BOOL ADOConn::GetRecordSet(CString strSQL)//获得记录集
{
try{
m_pCommand->CommandText=(_bstr_t)strSQL;
m_pCommand->ActiveConnection=m_pConnection;
m_pCommand->CommandType=adCmdText;
m_pRecordset=m_pCommand->Execute(NULL,NULL,adCmdText);
return true;
}catch(_com_error e)
{
AfxMessageBox("执行select语句失败");
return false;
}
}
int ADOConn::GetRecordCount()//获得记录数
{
DWORD nRows = 0;
nRows=m_pRecordset->GetRecordCount();
if(nRows==-1)
{
nRows=0;
if(m_pRecordset->adoEOF!=VARIANT_TRUE) m_pRecordset->MoveFirst();
while(m_pRecordset->adoEOF!=VARIANT_TRUE)
{
nRows++;
m_pRecordset->MoveNext();
}
if(nRows>0)m_pRecordset->MoveFirst();
}
return nRows;
}
//判断表TableName中是否存在字段KeyName的值为KeyValue的记录
BOOL ADOConn::RecordExist(CString TableName,CString KeyName,CString KeyValue)
{
CString countstr;
countstr="select * from "+TableName+"where"+KeyName+"=\'"+KeyValue+"\'";
BOOL ret =GetRecordSet(countstr);
if(ret)
{
int ret2=GetRecordCount();
if(ret2) return true;
else return false;
}
else return false;
}
BOOL ADOConn::MoveFirst()//移动到第一条记录
{
try{
m_pRecordset->MoveFirst();
return true;
}catch(_com_error e){
AfxMessageBox("结果集移到第一个失败");
return false;
}
}
BOOL ADOConn::MoveNext()//移动到下一条记录
{
try{
m_pRecordset->MoveNext();
return true;
}catch(_com_error e){
AfxMessageBox("结果集移到下一个失败");
return false;
}
}
BOOL ADOConn::Close()//关闭记录集
{
try{
m_pRecordset->Close();
return true;
}catch(_com_error e){
AfxMessageBox("关系结果集失败");
return false;
}
}
BOOL ADOConn::CloseADOConnection()//关闭连接
{
try{
if(m_pConnection->State)
{
m_pConnection->Close();
m_pConnection=NULL;
return true;
}
else{
AfxMessageBox("关闭数据库失败");
return false;
}
}catch(_com_error e){
AfxMessageBox("关闭数据库失败");
return false;
}
}
void ADOConn::dump_com_error(_com_error &e) //错误详细信息
{
CString ErrorStr;
_bstr_t bstrSource(e.Source());
_bstr_t bstrDescription(e.Description());
ErrorStr.Format( "/n/tADO Error/n/tCode = %08lx/n/tCode meaning = %s/n/tSource = %s/n/tDescription = %s/n/n",
e.Error(), e.ErrorMessage(), (LPCTSTR)bstrSource, (LPCTSTR)bstrDescription );
//在调试窗口中打印错误信息,在Release版中可用DBGView查看错误信息
::OutputDebugString((LPCTSTR)ErrorStr);
#ifdef _DEBUG
AfxMessageBox(ErrorStr, MB_OK | MB_ICONERROR);
#endif
}
ADOConn.cpp---------------------------------------------------------------------------------
3.编写代码连接数据库(这里我用的是ACCESS数据库)
这里我们可以在任意.CPP(源文件)中声明ADOConn ado;
然后在其他.CPP中使用的时候,只需要在头部加上extern ADOConn ado;
当然,在定义的类中同样可以使用,举例如下:
然后进行连接数据库的代码如下:
//进行数据库连接
if(!AfxOleInit())
{
AfxMessageBox("OLE initialzation failed");
return FALSE;
}
CString str="DSN=rapidquery";//这个字符串中的rapidquery就是我们之前设置的数据源的名称
ado.OnInitADOConn(str);//调用dao对象去连接数据库,连接成功会提示,连接失败也会提示。
这是连接成功的提示
下面的是我们access数据库中的信息
这是我们程序从数据库中读出的信息