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);
}