SQL Server backup and restore

本文介绍了一种使用Delphi实现SQL Server数据库备份与恢复的线程化方法。通过创建自定义线程类,实现了数据库操作的异步执行,提高了应用程序的响应速度。文章详细展示了如何设置连接字符串、构造SQL语句以及处理执行过程中的异常。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 This operation is in a thread, for it must take much time.

 

Codes below:

 

 

 

  1. unit CustomSQLThread;
  2. {----------------------------------------------------------
  3.  - Example for using this unit                            -
  4.  - procedure BackupDB;                                    -
  5.  - var                                                    -
  6.  -   BackupThread : TCustomSQLBackupThread;               -
  7.  - begin                                                  -
  8.  -   BackupThread := TCustomSQLBackupThread.Create(true); -
  9.  -   with BackupThread do                                 -
  10.  -   begin                                                -
  11.  -     FreeOnTerminate := true;                           -
  12.  -     DBHost := '127.0.0.1';                             -
  13.  -     UserID := 'sa';                                    -
  14.  -     UserPwd := '';                                     -
  15.  -     DatabaseName := '';                                -
  16.  -     BackupFileName := 'C:/MyBackup';                   -
  17.  -     Execute;                                           -
  18.  -   end;                                                 -
  19.  - end;                                                   -
  20.  ----------------------------------------------------------}
  21. Interface
  22. Uses
  23.   Classes, SysUtils, DB, ADODB, Windows, ShellAPI, Registry;
  24. Type
  25.   { SQL Server operations state }
  26.   TSQLStates = (ssSuccess, ssFail);
  27.   { thread of backup SQL Server database }
  28.   TCustomSQLBackupThread = Class(TThread)
  29.   private
  30.     FDatabaseName: String;
  31.     FUserPwd: String;
  32.     FBackupFileName: String;
  33.     FUserID: String;
  34.     FDBHost: String;
  35.     FBackupState: TSQLStates;
  36.     FErrorMessage: String;
  37.   protected
  38.     { Run thread }
  39.     procedure Execute; override;
  40.   public
  41.     Constructor Create(CreateSuspended: Boolean);
  42.     Property BackupState: TSQLStates read FBackupState;
  43.     Property ErrorMessage: String read FErrorMessage;
  44.   published
  45.     { The host name of SQL Server }
  46.     Property DBHost: String read FDBHost write FDBHost;
  47.     { The user name for login SQL Server }
  48.     Property UserID: String read FUserID write FUserID;
  49.     { The user password for login SQL Server}
  50.     Property UserPwd: String read FUserPwd write FUserPwd;
  51.     { The database's name }
  52.     Property DatabaseName: String read FDatabaseName write FDatabaseName;
  53.     { Where you put the backup file at }
  54.     Property BackupFileName: String read FBackupFileName write FBackupFileName;
  55.   end;
  56.   { thread of restore SQL Server database }
  57.   TCustomSQLRestoreThread = Class(TThread)
  58.   private
  59.     FDatabaseName: String;
  60.     FUserPwd: String;
  61.     FBackupFileName: String;
  62.     FUserID: String;
  63.     FDBHost: String;
  64.     FBackupState: TSQLStates;
  65.     FErrorMessage: String;
  66.     FLogicDatabaseName: String;
  67.     FLogicLogName: String;
  68.   protected
  69.     { Run thread }
  70.     procedure Execute; override;
  71.   public
  72.     Constructor Create(CreateSuspended: Boolean);
  73.     Property BackupState: TSQLStates read FBackupState;
  74.     Property ErrorMessage: String read FErrorMessage;
  75.   published
  76.     { The host name of SQL Server }
  77.     Property DBHost: String read FDBHost write FDBHost;
  78.     { The user name for login SQL Server }
  79.     Property UserID: String read FUserID write FUserID;
  80.     { The user password for login SQL Server}
  81.     Property UserPwd: String read FUserPwd write FUserPwd;
  82.     { The database's name }
  83.     Property DatabaseName: String read FDatabaseName write FDatabaseName;
  84.     { Where you put the backup file at }
  85.     Property BackupFileName: String read FBackupFileName write FBackupFileName;
  86.     { The logic database file name }
  87.     Property LogicDatabaseName: String read FLogicDatabaseName write FLogicDatabaseName;
  88.     { The logic log file name }
  89.     Property LogicLogName: String read FLogicLogName write FLogicLogName;
  90.   end;
  91. { Global methods }
  92. { whether SQL Server installed or not }
  93. function SQLServerInstalled: Boolean;
  94. { get SQL Server install path if installed }
  95. function GetSQLServerPath: String;
  96. { Services operations }
  97. procedure SQLServicesOperation(CommandStr: String);
  98. Implementation
  99. resourcestring
  100.   { connection string }
  101.   ConnStr =
  102.     'Provider=SQLOLEDB.1;' +
  103.     'Data Source=%s;' +                                         // Host Name
  104.       'Persist Security Info=True;' +
  105.     'User ID=%s;' +                                                 // User Name
  106.       'Password=%s;' +                                                 // User Password
  107.       'Initial Catalog=%s';                                     // DatabaseName
  108.   { backup database T-SQL codes }
  109.   BackupStr =
  110.     'BACKUP DATABASE [%s] TO ' +                         // Database Name
  111.       'DISK=N'#39'%s'#39' WITH NOINIT,' +         // Physics File Name
  112.       'NOUNLOAD,NOSKIP,STATS=10,NOFORMAT';
  113.   { restore database T-SQL codes }
  114.   RestoreStr =
  115.     'RESTORE DATABASE [%s] FROM ' +                 // Database Name
  116.       'DISK=N'#39'%s'#39' WITH FILE=1,' +         // Physics File Name
  117.       'NOUNLOAD,STATS=10,RECOVERY,' +
  118.     'MOVE '#39'%s'#39' to '#39'%s'#39',' +     // Logic Database Name
  119.       'MOVE '#39'%s'#39' to '#39'%s'#39;             // Logic Log Name
  120.   { restore database without move file T-SQL codes }
  121.   RestoreStr2 =
  122.     'RESTORE DATABASE [%s] FROM ' +                 // Database Name
  123.       'DISK=N'#39'%s'#39' WITH FILE=1,' +         // Physics File Name
  124.       'NOUNLOAD,STATS=10,RECOVERY';
  125. { Global methods }
  126. /// <summary>
  127. /// whether SQL Server installed
  128. /// </summary>
  129. /// <returns>installed(true)/not installed(false)</returns>
  130. function SQLServerInstalled: Boolean;
  131. Var
  132.   Reg: TRegistry;
  133.   Path: String;
  134. begin
  135.   Reg := TRegistry.Create;
  136.   Reg.RootKey := HKEY_LOCAL_MACHINE;
  137.   Reg.OpenKey('SOFTWARE/Microsoft/MSSQLServer/Setup'true);
  138.   Path := Reg.ReadString('SQLPath');
  139.   if (Path <> ''and (DirectoryExists(Path)) then
  140.     Result := true
  141.   Else
  142.     Result := false;
  143.   Reg.CloseKey;
  144.   Reg.Free;
  145. end;
  146. /// <summary>
  147. /// get SQL Server installed path
  148. /// </summary>
  149. /// <returns>path(if installed)</returns>
  150. function GetSQLServerPath: String;
  151. Var
  152.   Reg: TRegistry;
  153.   Path: String;
  154. begin
  155.   if Not SQLServerInstalled then
  156.   begin
  157.     Result := '';
  158.     Exit;
  159.   end;
  160.   Reg := TRegistry.Create;
  161.   Reg.RootKey := HKEY_LOCAL_MACHINE;
  162.   Reg.OpenKey('SOFTWARE/Microsoft/MSSQLServer/Setup'true);
  163.   Path := Reg.ReadString('SQLPath');
  164.   Result := Path + '/Data/';
  165.   Reg.CloseKey;
  166.   Reg.Free;
  167. end;
  168. /// <summary>
  169. /// do operations order with commandstr
  170. /// </summary>
  171. /// <param name="CommandStr">command line</param>
  172. procedure SQLServicesOperation(CommandStr: String);
  173. Var
  174.   sCommandLine: String;
  175.   bCreateProcess: Boolean;
  176.   lpStartupInfo: TStartupInfo;
  177.   lpProcessInformation: TProcessInformation;
  178. begin
  179.   sCommandLine := CommandStr;
  180.   // fill record space
  181.   FillChar(lpStartupInfo, SizeOf(TStartupInfo), #0);
  182.   lpStartupInfo.cb := SizeOf(TStartupInfo);
  183.   lpStartupInfo.dwFlags := STARTF_USESHOWWINDOW;
  184.   lpStartupInfo.wShowWindow := SW_HIDE;
  185.   // create process
  186.   bCreateProcess := CreateProcess(Nil, PChar(sCommandLine), Nil, Nil, true, CREATE_NEW_CONSOLE Or NORMAL_PRIORITY_CLASS, Nil, Nil, lpStartupInfo, lpProcessInformation);
  187.   // wait for process finished
  188.   if bCreateProcess then
  189.     WaitForSingleObject(lpProcessInformation.hProcess, INFINITE);
  190. end;
  191. { TCustomDBBackupRestoreThread }
  192. Constructor TCustomSQLBackupThread.Create(CreateSuspended: Boolean);
  193. begin
  194.   Inherited Create(CreateSuspended);
  195.   // if you want to get the state when thread finished,
  196.   // add a method of type TNotifyEvent and bind it to:
  197.   // OnTerminate event of this class.
  198. end;
  199. procedure TCustomSQLBackupThread.Execute;
  200. Var
  201.   Qry: TADOQuery;
  202. begin
  203.   Qry := TADOQuery.Create(Nil);
  204.   With Qry Do
  205.   begin
  206.     ConnectionString := Format(ConnStr,
  207.       [DBHost, UserID, UserPwd, DatabaseName]);
  208.     SQL.Text := Format(BackupStr, [DatabaseName, BackupFileName]);
  209.     Try
  210.       ExecSQL;
  211.       FBackupState := ssSuccess;
  212.       FErrorMessage := '';
  213.     Except
  214.       On E: Exception Do
  215.       begin
  216.         FBackupState := ssFail;
  217.         FErrorMessage := E.Message;
  218.       end;
  219.     end;
  220.     Free;
  221.   end;
  222. end;
  223. { TCustomSQLRestoreThread }
  224. Constructor TCustomSQLRestoreThread.Create(CreateSuspended: Boolean);
  225. begin
  226.   Inherited Create(CreateSuspended);
  227.   // if you want to get the state when thread finished,
  228.   // add a method of type TNotifyEvent and bind it to:
  229.   // OnTerminate event of this class.
  230. end;
  231. procedure TCustomSQLRestoreThread.Execute;
  232. Var
  233.   Qry: TADOQuery;
  234. begin
  235.   // Stop SQL Server Services
  236.   // this operation may let all user connects logoff.
  237.   SQLServicesOperation('net stop MSSQLSERVER');
  238.   // restart SQL Server
  239.   SQLServicesOperation('net start MSSQLSERVER');
  240.   // Restore database
  241.   Qry := TADOQuery.Create(Nil);
  242.   With Qry Do
  243.   begin
  244.     // if you want to restore "master"
  245.     // change "master" to other Database's name
  246.     ConnectionString := Format(ConnStr,
  247.       [DBHost, UserID, UserPwd, 'master']);
  248.     SQL.Text := Format(RestoreStr,
  249.       [DatabaseName, BackupFileName, LogicDatabaseName, LogicLogName]);
  250.     Try
  251.       ExecSQL;
  252.       FBackupState := ssSuccess;
  253.       FErrorMessage := '';
  254.     Except
  255.       SQL.Text := Format(RestoreStr2, [DatabaseName, BackupFileName]);
  256.       Try
  257.         ExecSQL;
  258.         FBackupState := ssSuccess;
  259.         FErrorMessage := '';
  260.       Except
  261.         On E: Exception Do
  262.         begin
  263.           FBackupState := ssFail;
  264.           FErrorMessage := E.Message;
  265.         end;
  266.       end;
  267.     end;
  268.     Free;
  269.   end;
  270. end;
  271. end.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值