C++ ADO SQL数据库备份 数据库还原

前提:需掌握导入ADO库,连接数据库方法。

数据库备份的SQL语句:

backup database 数据库名 to disk = '文件路径/文件名'

数据库还原的 SQL语句:

restore database 数据库名 from disk = '备份文件' with replace

备份示例: _connectptr 执行Execute方法,实现备份SQL语句。

CString sqlback = "backup database Flight to disk = '" + FilePath + FileName + ".bak'";
		
		theApp.m_pConn->Execute(_bstr_t(sqlback), NULL, adCmdText);


还原示例:


如果当前_connectptr 已经连接了要还原的数据库,那么就要把这些指针全部释放,重新连接一个非还原数据库的数据库。比如master


还原时,如果数据库是打开的,要关闭。

                if (theApp.m_pRec->State)
			theApp.m_pRec->Close();
		if (theApp.m_pConn->State)
		{
			theApp.m_pConn->Close();
			theApp.m_pConn = NULL;
		}
                //先释放掉指针
                //再次连接新数据库
		theApp.m_pConn.CreateInstance(__uuidof(Connection));
		theApp.m_pConn->Open("Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=master;",
               "", "", adModeUnknown);///连接数据库
		CString sqlrestore = "restore database [Flight] from disk = '" + FilePath + FileName + ".bak' with replace";
		theApp.m_pConn->Execute(_bstr_t(sqlrestore), NULL, adCmdText);

		AfxMessageBox("还原成功");
               //还原成功后可以再次连接原本的数据库
		if (theApp.m_pConn->State)
		{
			theApp.m_pConn->Close();
			theApp.m_pConn = NULL;
		}
		if (theApp.pMyCommand->State)
		{
			theApp.pMyCommand->Release();
			theApp.pMyCommand = NULL;
		}
		try{
			//此处需要更改数据库
			theApp.m_pConn.CreateInstance(__uuidof(Connection));//	创建连接对象
			theApp.m_pConn->Open("Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=Flight;",
                         "", "", adModeUnknown);///连接数据库
			theApp.pMyCommand.CreateInstance(__uuidof(Command));
			theApp.pMyCommand->CommandTimeout = 5;
			theApp.pMyCommand->ActiveConnection = theApp.m_pConn;
			
		}
		catch (_com_error e){
			AfxMessageBox("	数据库连接失败!");
	
		}
		theApp.m_pRec.CreateInstance(__uuidof(Recordset));
	

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值