有没有办法使用FireDAC备份和恢复数据库?
我正在使用Delphi 10.1 Berlin并连接到MSSQL Server。理想情况下,它会备份数据库的所有有趣属性(记录,索引等),但是只需备份和恢复数据的解决方案就可以了(我可以在恢复之前重新创建所有元数据)。
答案 0 :(得分:3)
我承认我对你的q有点疑惑,因为答案似乎有点太容易了,即
使用FireDAC的TDFConnection
执行SqlServer TransactSql脚本来备份和恢复数据库。我希望你不要把它视为作弊;)
示例项目代码
type
TForm1 = class(TForm)
FDConnection1: TFDConnection;
btnBackUp: TButton;
btnRestore: TButton;
FDMetaInfoQuery1: TFDMetaInfoQuery;
FDPhysMSSQLDriverLink1: TFDPhysMSSQLDriverLink;
DBGrid1: TDBGrid; // connected to DataSource1
DataSource1: TDataSource; // connected to FDMetaInfoQuery1
Memo1: TMemo;
procedure btnBackUpClick(Sender: TObject);
procedure btnRestoreClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
[...]
const
scBackUpPath = 'D:\MSSql2014\Backup\';
scBackupExtn = '.Bak';
procedure TForm1.Log(const Msg : String);
begin
Memo1.Lines.Add(Msg);
end;
function TForm1.DatabaseName: String;
begin
Result := FDMetaInfoQuery1.FieldByName('Catalog_Name').AsString;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
FDMetaInfoQuery1.MetaInfoKind := mkCatalogs; // gets list of databases
FDConnection1.Connected := True;
end;
procedure TForm1.BackupDB(const DBName: String);
var
FileName,
Sql : String;
begin
FileName := scBackUpPath + DBName + scBackUpExtn;
Sql := 'backup database %s to disk = ''%s''';
Sql := Format(Sql, [DBName, FileName]);
Log('Backing up ' + DBName + ' using SQL: ' + Sql);
try
Screen.Cursor := crHourGlass;
Update;
FDConnection1.ExecSQL(Sql);
Log('Done');
finally
Screen.Cursor := crDefault;
end;
end;
procedure TForm1.btnBackUpClick(Sender: TObject);
begin
BackUpDB(DatabaseName);
end;
procedure TForm1.btnRestoreClick(Sender: TObject);
begin
RestoreDB(DatabaseName);
end;
procedure TForm1.RestoreDB(const DBName: String);
var
FileName,
Sql : String;
begin
FileName := scBackUpPath + DBName + scBackUpExtn;
if FileExists(FileName) then begin
// Note: beware the 'with replace' in the following
Sql := 'restore database %s from disk = ''%s'' with replace';
Sql := Format(Sql, [DBName, FileName]);
Log('Restoring ' + DBName + ' using SQL: ' + Sql);
try
Screen.Cursor := crHourGlass;
Update;
FDConnection1.ExecSQL(Sql);
Log('Done');
finally
Screen.Cursor := crDefault;
end;
end
else
Log('Backup file ' + FileName + ' not found!');
end;
显然,错误检查有点亮,但我相信你会明白这个想法。
在逐步淘汰之前,我会将Delphi自动化用于SqlServer的Sql-DMO库 这样做是因为很容易实现“%completed”等进度回调。
我还没有成功地使用Delphi的Sql_DOM的继任者SMO做任何有用的事情 这些天我会使用TADOConnection而不是FireDAC来做到这一点 因为获取数据库列表所需的行李较少 ADO错误集合提供了一种简单的方法来解决遇到的任何错误。