MFC采用ADO Command对象备份还原数据库SQL Server 2005

本文详细介绍了如何在特定应用程序中进行数据库备份和还原操作,包括生成备份文件、执行备份命令以及验证备份是否成功。同时,阐述了还原数据库前的必要步骤以及还原后的操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Command对象使用前的初始化
//声明Command智能指针变量
_CommandPtr pCommand;
//实例化该变量
m_pCommand.CreateInstance(__uuidof(Command));
//m_pConnection是已定义并实例化的Connection的智能指针变量
//给ActiveConnection赋值,指定数据库连接
m_pCommand->ActiveConnection = m_pConnection;
备份数据库:
void CDlgBRData::OnBnClickedBrBu()
{
// TODO: Add your control notification handler code here
UpdateData();
CString strSQL,strpath,FileName;
_variant_t RecordsAffected;
CTime time=CTime::GetCurrentTime(); //获取当前系统时间
FileName = time.Format("%Y%m%d%H%M"); //生成以当前系统时间为名称的备份文件名
//m_BakPath为备份文件所在文件夹路径
//初始化备份文件路径,如:C:\Program Files\Microsoft SQL Server\Backup\201104191640.bak
strpath.Format(_T("%s%s.bak"),m_BakPath,FileName); 
try {
strSQL.Format(_T("BACKUP DATABASE [宾馆管理系统] TO DISK = '%s'"),strpath);
//通过CommandText设置SQL命令
theApp.m_pCommand->CommandText = _bstr_t(strSQL);
//执行该命令
theApp.m_pCommand->Execute(NULL,NULL,adCmdText);
MessageBox(_T("备份成功!"),_T("提示"),MB_ICONEXCLAMATION);
}
catch(_com_error *e) {
MessageBox(e->Description());
return;
}
}
还原数据库:
void CDlgBRData::OnBnClickedBrRs()
{
// TODO: Add your control notification handler code here
UpdateData();
if(m_ResPath.IsEmpty()) {
MessageBox(_T("请选择备份文件"),_T("提示"),MB_ICONEXCLAMATION);
return;
}
CString strSQL;
//还原数据库前需断开所有数据库连接
strSQL.Format(_T("USE MASTER EXEC KILLSPID '宾馆管理系统'"));
try {
theApp.m_pCommand->CommandText = _bstr_t(strSQL);
theApp.m_pCommand->Execute(NULL,NULL,adCmdText);
}
catch(_com_error *e){
MessageBox(e->Description());
return;
}
//还原数据库
strSQL.Format(_T("RESTORE DATABASE [宾馆管理系统] FROM  DISK = '%s' WITH  FILE = 1,  NOUNLOAD,  REPLACE, STATS = 10"),m_ResPath);
try {
theApp.m_pCommand->CommandText = _bstr_t(strSQL);
theApp.m_pCommand->Execute(NULL,NULL,adCmdText);
}
catch(_com_error *e) {
MessageBox(e->Description());
return;
}
MessageBox(_T("还原成功,请重新启动本软件!"),_T("提示"),MB_ICONEXCLAMATION);
//还原后需重新启动进程,连接数据库
//给CMainFram发送关闭消息,CMainFram重载OnClose函数,实现软件重新启动
CMainFrame *pMain = (CMainFrame*)AfxGetMainWnd();
pMain->m_Restart = true;
::SendMessage(AfxGetMainWnd()->m_hWnd,WM_CLOSE,0,0);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值