如何实现SQL Server数据库的备份与恢复
备份:
procedure TBackupFrm.BitBtn2Click(Sender: TObject);
begin
if Edit1.Text= ' then
begin
Showmessage('无选择要保存的文件名');
exit;
end;
try
try
dmData.adoQryTmp.Active:= false;
dmData.adoQryTmp.SQL.Clear;
dmData.adoQryTmp.SQL.Add('BACKUP DATABASE [dzyl] TO DISK = ''+edit1.text+'' WITH INIT');
dmData.adoQryTmp.ExecSQL;
finally
begin
dmData.adoQryTmp.Active:= false;
Showmessage('数据库备份成功!');
end;
end;
except
on e:exception do
begin
ShowMessage('数据库备份失败!');
end;
end;
end;
---------------------------
恢复
procedure TBackupFrm.BitBtn4Click(Sender: TObject);
begin
if Edit2.Text = ' then
begin
showmessage('未选择要恢复的数据库文件!');
exit;
end;
with dmData do
begin
try
adocmmd.CommandText:='use master';
adocmmd.Execute;
adocmmd.CommandText:='alter database dzyl set offline with rollback immediate';
adocmmd.Execute;
adocmmd.CommandText:='restore database dzyl from disk= ''+edit2.Text+'' with
recovery ';
adocmmd.Execute;
adocmmd.CommandText:=' alter database dzyl set online with rollback immediate';
adocmmd.Execute;
showmessage('数据库恢复成功!');
application.Terminate;
except
on e:exception do
begin
showmessage('数据库恢复失败!'+e.Message);
end;
end;
end;
其中dmData.adoQryTmp连接的是系统MASTER数据库,备份还原之前应该关闭要备份还原的AdoConn数据库
连接AdoConn.Connected:=False;
------------------------------------------------
另一方法:
备份如下:
try
backupString := 'BACKUP DATABASE [Paper] TO DISK = N''+edit1.Text+'' WITH
INIT , NOUNLOAD , NAME = N'Paper 备份', NOSKIP , STATS = 10, NOFORMAT';
adoquery1.Close;
adoquery1.SQL.Clear;
adoquery1.SQL.Add(backupString);
ADOQuery1.Prepared;
adoquery1.ExecSQL;
application.MessageBox('备份成功。','提示',0);
except
application.MessageBox('备份出错!请重新备份数据。','出错',0);
end;
---------------------------
还原如下:
if opendialog1.Execute then
begin
try
adoquery1.Close();
adoquery1.SQL.Clear;
adoquery1.SQL.Add('use master');
adoquery1.Prepared;
adoquery1.ExecSQL;
restorestring := 'RESTORE DATABASE [Paper] FROM DISK =
N''+opendialog1.FileName+'' WITH FILE = 1, NOUNLOAD , STATS = 10, REPLACE,RECOVERY';
self.ADOCommand1.CommandText := restoreString;
adocommand1.Execute;
application.MessageBox('还原数据成功','提示',0);
adoquery1.Close();
adoquery1.SQL.Clear;
adoquery1.SQL.Add('use paper');
adoquery1.Prepared;
adoquery1.ExecSQL;
except
application.MessageBox('还原数据出错!请重新还原,并停止一切的数据操作!
','提示',0);
end;
end;