前提:需掌握导入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));