个人博客地址 www.tmbcode.com
MFC连接SQLServer数据库及操作数据库信息
一、测试环境
操作系统:WindowsXP
数据库:SQLServer2005
IDE:VC++6.0
二、初始化ADO
在.h文件中添加:
_ConnectionPtrm_pConnection;
_RecordsetPtrm_pRst;
在.cpp中添加函数:
BOOLXXXApp::InitADO()
{
CoInitialize(NULL);
HRESULThrpC,hrpR;
hrpC=m_pConnection.CreateInstance(__uuidof(Connection));
hrpR=m_pRst.CreateInstance(__uuidof(Recordset));
if(SUCCEEDED(hrpC)&& SUCCEEDED(hrpR))
returnTRUE;
returnFALSE;
}
三、连接数据库的函数
boolXXXApp::ConnectMDBDatabase()
{
CStringtemp;
_variant_tvar;
CStringsql;
sql.Format("driver={SQLServer};Server=TEST;DATABASE=TEST;UID=sa;PWD=123456");
try
{
if(((XXXApp*)AfxGetApp())->m_pConnection->State)
((XXXApp*)AfxGetApp())->m_pConnection->Close();
((XXXApp*)AfxGetApp())->m_pConnection->ConnectionTimeout=15;
((XXXApp *)AfxGetApp())->m_pConnection->Open((char*)(LPCTSTR)sql,"","",adModeUnknown);
}
catch(_com_errore)
{
returnFALSE;
}
returnTRUE;
}
四、建立连接(在InitInstance()中添加)
//初始化ADO
if(!((XXXApp*)AfxGetApp())->InitADO())
{
returnFALSE;
}
//连接生产数据库
if(!this->ConnectMDBDatabase())
{
AfxMessageBox("连接生产数据库失败",MB_OK,0);
returnFALSE;
}
五、操作数据库信息
BOOL XXX::GetOrderList()//查询和插入
{
CStringtemp;
_variant_tvar;
CStringsql;
try
{
sql.Format("select* from Table where Name='test' andEnable = 1");
if(((XXXApp*)AfxGetApp())->m_pRst->State)
((XXXApp*)AfxGetApp())->m_pRst->Close();
((XXXApp*)AfxGetApp())->m_pRst=((XXXApp *)AfxGetApp())->m_pConnection->Execute((_bstr_t)sql,NULL,adCmdText);
while(!((XXXApp*)AfxGetApp())->m_pRst->adoEOF)
{
var= ((XXXApp *)AfxGetApp())->m_pRst->GetCollect("Class");
temp=VariantToCString(var);
this->m_ctrClass.AddString(temp);
var= ((XXXApp *)AfxGetApp())->m_pRst->GetCollect("Age");
this->age=var.intval();
((XXXApp*)AfxGetApp())->m_pRst->MoveNext();
}
if(((XXXApp*)AfxGetApp())->m_pRst->State)
((XXXApp*)AfxGetApp())->m_pRst->Close();
}
catch(_com_errore)
{
returnFALSE;
}
sql.Format("INSERTINTO Student (Name,Adress) VALUES ('%s','%s')", \
this->name,this->adress);
try
{
if(((XXXApp*)AfxGetApp())->m_pRst->State)
((XXXApp *)AfxGetApp())->m_pRst->Close();
((XXXApp*)AfxGetApp())->m_pConnection->Execute((_bstr_t)sql,NULL,adCmdText);
if(((XXXApp*)AfxGetApp())->m_pRst->State)
((XXXApp*)AfxGetApp())->m_pRst->Close();
}
catch(_com_errore)
{
MessageBox("录入Student表失败","提示",MB_ICONHAND);
returnFALSE;
}
returnTRUE;
}
Update和Delete以此类推,这里就不做详细介绍了。
此文章只是个人在实际项目中所总结的一点小小经验,代码不是非常的严谨,觉得有帮助的可以参考一下,觉得有问题的可以给我留言,便于我做出改善,大家相互学习。