数据备份还原线程控件

 
  1. 控件代码:
  2. unit DHibernateBackupRestore;
  3. interface
  4. uses
  5.    Windows, Messages, SysUtils, Classes, dhibernateSQLThread;
  6. type
  7.    TDHibernateBackupRestore = class(tcomponent)
  8.    private
  9.      FAbout: string;
  10.      FBackupFileName: string;
  11.      FDatabaseName: string;
  12.      FUserPwd: string;
  13.      FUserID: string;
  14.      FDBHost: string;
  15.      FOnFinishBackup: TNotifyEvent;
  16.      FLogicDatabaseName: string;
  17.      FLogicLogName: string;
  18.      FOnFinishRestore: TNotifyEvent;
  19.      FOnBeginBackup: TNotifyEvent;
  20.      FOnBeginRestore: TNotifyEvent;
  21.      { Private declarations }
  22.    protected
  23.      { Protected declarations }
  24.    public
  25.      constructor Create(AOwner: TComponent); override;
  26.      destructor Destroy; override;
  27.      procedure Backup;
  28.      procedure Restore;
  29.    published
  30.      property About: string read FAbout write FAbout;
  31.      property DBHost: string read FDBHost write FDBHost;
  32.      property UserID: string read FUserID write FUserID;
  33.      property UserPwd: string read FUserPwd write FUserPwd;
  34.      property DatabaseName: string read FDatabaseName write FDatabaseName;
  35.      property BackupFileName: string read FBackupFileName write FBackupFileName;
  36.      property OnBeginBackup: TNotifyEvent read FOnBeginBackup write
  37.        FOnBeginBackup;
  38.      property OnFinishBackup: TNotifyEvent read FOnFinishBackup write
  39.        FOnFinishBackup;
  40.      property LogicDatabaseName: string read FLogicDatabaseName write
  41.        FLogicDatabaseName;
  42.      property LogicLogName: string read FLogicLogName write FLogicLogName;
  43.      property OnBeginRestore: TNotifyEvent read FOnBeginRestore write
  44.        FOnBeginRestore;
  45.      property OnFinishRestore: TNotifyEvent read FOnFinishRestore write
  46.        FOnFinishRestore;
  47.    end;
  48. implementation
  49. { TDHibernateBackupRestore }
  50. procedure TDHibernateBackupRestore.Backup;
  51. var
  52.    backupThread       : TCustomSQLBackupThread;
  53. begin
  54.    if Assigned(OnBeginBackup) then
  55.      OnBeginBackup(Self);
  56.    backupThread := TCustomSQLBackupThread.Create(True);
  57.    with backupThread do
  58.    begin
  59.      FreeOnTerminate := True;
  60.      DBHost := self.FDBHost;
  61.      UserID := self.FUserID;
  62.      UserPwd := self.FUserPwd;
  63.      DatabaseName := self.FDatabaseName;
  64.      BackupFileName := self.FBackupFileName;
  65.      if Assigned(OnFinishBackup) then
  66.        OnFinish := OnFinishBackup;
  67.      Execute;
  68.    end;
  69. end;
  70. constructor TDHibernateBackupRestore.Create(AOwner: TComponent);
  71. begin
  72.    inherited Create(AOwner);
  73. end;
  74. destructor TDHibernateBackupRestore.Destroy;
  75. begin
  76.    inherited Destroy;
  77. end;
  78. procedure TDHibernateBackupRestore.Restore;
  79. var
  80.    RestoreThread      : TCustomSQLRestoreThread;
  81. begin
  82.    if Assigned(OnBeginRestore) then
  83.      OnBeginRestore(Self);
  84.    RestoreThread := TCustomSQLRestoreThread.Create(True);
  85.    with RestoreThread do
  86.    begin
  87.      FreeOnTerminate := True;
  88.      DBHost := self.FDBHost;
  89.      UserID := self.FUserID;
  90.      UserPwd := self.FUserPwd;
  91.      DatabaseName := self.FDatabaseName;
  92.      BackupFileName := self.FBackupFileName;
  93.      LogicDatabaseName := Self.FLogicDatabaseName;
  94.      LogicLogName := Self.FLogicLogName;
  95.      if Assigned(OnFinishRestore) then
  96.        OnFinish := OnFinishRestore;
  97.      Execute;
  98.    end;
  99. end;
  100. end.
  101. 内部线程代码:
  102. unit DHibernateSQLThread;
  103. {----------------------------------------------------------
  104. - Example for using this unit                             -
  105. - procedure BackupDB;                                     -
  106. - var                                                     -
  107. -    BackupThread : TCustomSQLBackupThread;                -
  108. - begin                                                   -
  109. -    BackupThread := TCustomSQLBackupThread.Create(true); -
  110. -    with BackupThread do                                  -
  111. -    begin                                                 -
  112. -      FreeOnTerminate := true;                            -
  113. -      DBHost := '127.0.0.1';                              -
  114. -      UserID := 'sa';                                     -
  115. -      UserPwd := '';                                      -
  116. -      DatabaseName := '';                                 -
  117. -      BackupFileName := 'C:/MyBackup';                    -
  118. -      Execute;                                            -
  119. -    end;                                                  -
  120. - end;                                                    -
  121. ----------------------------------------------------------}
  122. interface
  123. uses
  124.    Classes, SysUtils, DB, ADODB, Windows, ShellAPI, Registry;
  125. type
  126.    { SQL Server operations state }
  127.    TSQLStates = (ssSuccess, ssFail);
  128.    { thread of backup SQL Server database }
  129.    TCustomSQLBackupThread = class(TThread)
  130.    private
  131.      FDatabaseName: string;
  132.      FUserPwd: string;
  133.      FBackupFileName: string;
  134.      FUserID: string;
  135.      FDBHost: string;
  136.      FBackupState: TSQLStates;
  137.      FErrorMessage: string;
  138.      FOnFinish: TNotifyEvent;
  139.    protected
  140.      { Run thread }
  141.    public
  142.      constructor Create(CreateSuspended: Boolean);
  143.      procedure Execute; override;
  144.      property BackupState: TSQLStates read FBackupState;
  145.      property ErrorMessage: string read FErrorMessage;
  146.    published
  147.      { The host name of SQL Server }
  148.      property DBHost: string read FDBHost write FDBHost;
  149.      { The user name for login SQL Server }
  150.      property UserID: string read FUserID write FUserID;
  151.      { The user password for login SQL Server}
  152.      property UserPwd: string read FUserPwd write FUserPwd;
  153.      { The database's name }
  154.      property DatabaseName: string read FDatabaseName write FDatabaseName;
  155.      { Where you put the backup file at }
  156.      property BackupFileName: string read FBackupFileName write FBackupFileName;
  157.      { finish thread }
  158.      property OnFinish: TNotifyEvent read FOnFinish write FOnFinish;
  159.    end;
  160.    { thread of restore SQL Server database }
  161.    TCustomSQLRestoreThread = class(TThread)
  162.    private
  163.      FDatabaseName: string;
  164.      FUserPwd: string;
  165.      FBackupFileName: string;
  166.      FUserID: string;
  167.      FDBHost: string;
  168.      FBackupState: TSQLStates;
  169.      FErrorMessage: string;
  170.      FLogicDatabaseName: string;
  171.      FLogicLogName: string;
  172.      FOnFinish: TNotifyEvent;
  173.    protected
  174.      { Run thread }
  175.    public
  176.      constructor Create(CreateSuspended: Boolean);
  177.      procedure Execute; override;
  178.      property BackupState: TSQLStates read FBackupState;
  179.      property ErrorMessage: string read FErrorMessage;
  180.    published
  181.      { The host name of SQL Server }
  182.      property DBHost: string read FDBHost write FDBHost;
  183.      { The user name for login SQL Server }
  184.      property UserID: string read FUserID write FUserID;
  185.      { The user password for login SQL Server}
  186.      property UserPwd: string read FUserPwd write FUserPwd;
  187.      { The database's name }
  188.      property DatabaseName: string read FDatabaseName write FDatabaseName;
  189.      { Where you put the backup file at }
  190.      property BackupFileName: string read FBackupFileName write FBackupFileName;
  191.      { The logic database file name }
  192.      property LogicDatabaseName: string read FLogicDatabaseName write
  193.        FLogicDatabaseName;
  194.      { The logic log file name }
  195.      property LogicLogName: string read FLogicLogName write FLogicLogName;
  196.      { finish thread }
  197.      property OnFinish: TNotifyEvent read FOnFinish write FOnFinish;
  198.    end;
  199.    { Global methods }
  200.    { whether SQL Server installed or not }
  201. function SQLServerInstalled: Boolean;
  202. { get SQL Server install path if installed }
  203. function GetSQLServerPath: string;
  204. { Services operations }
  205. procedure SQLServicesOperation(CommandStr: string);
  206. { server data root }
  207. function GetSQLServerDataRoot:string;
  208. implementation
  209. resourcestring
  210.    { connection string }
  211.    ConnStr            =
  212.      'Provider=SQLOLEDB.1;' +
  213.      'Data Source=%s;' +                  // Host Name
  214.    'Persist Security Info=True;' +
  215.      'User ID=%s;' +                      // User Name
  216.    'Password=%s;' +                       // User Password
  217.    'Initial Catalog=%s';                  // DatabaseName
  218.    { backup database T-SQL codes }
  219.    BackupStr          =
  220.      'BACKUP DATABASE [%s] TO ' +         // Database Name
  221.    'DISK=N'#39'%s'#39' WITH NOINIT,' +    // Physics File Name
  222.    'NOUNLOAD,NOSKIP,STATS=10,NOFORMAT';
  223.    { restore database T-SQL codes }
  224.    RestoreStr         =
  225.      'RESTORE DATABASE [%s] FROM ' +      // Database Name
  226.    'DISK=N'#39'%s'#39' WITH FILE=1,' +    // Physics File Name
  227.    'NOUNLOAD,STATS=10,RECOVERY,' +
  228.      'MOVE '#39'%s'#39' to '#39'%s'#39',' + // Logic Database Name
  229.    'MOVE '#39'%s'#39' to '#39'%s'#39;     // Logic Log Name
  230.    { restore database without move file T-SQL codes }
  231.    RestoreStr2        =
  232.      'RESTORE DATABASE [%s] FROM ' +      // Database Name
  233.    'DISK=N'#39'%s'#39' WITH FILE=1,' +    // Physics File Name
  234.    'NOUNLOAD,STATS=10,RECOVERY';
  235.    { Global methods }
  236.    /// <summary>
  237.    /// whether SQL Server installed
  238.    /// </summary>
  239.    /// <returns>installed(true)/not installed(false)</returns>
  240. function SQLServerInstalled: Boolean;
  241. var
  242.    Reg                : TRegistry;
  243.    Path               : string;
  244. begin
  245.    Reg := TRegistry.Create;
  246.    Reg.RootKey := HKEY_LOCAL_MACHINE;
  247.    Reg.OpenKey('SOFTWARE/Microsoft/MSSQLServer/Setup'true);
  248.    Path := Reg.ReadString('SQLPath');
  249.    if (Path <> ''and (DirectoryExists(Path)) then
  250.      Result := true
  251.    else
  252.      Result := False;
  253.    Reg.CloseKey;
  254.    Reg.Free;
  255. end;
  256. /// <summary>
  257. /// get SQL Server installed path
  258. /// </summary>
  259. /// <returns>path(if installed)</returns>
  260. function GetSQLServerPath: string;
  261. var
  262.    Reg                : TRegistry;
  263.    Path               : string;
  264. begin
  265.    if not SQLServerInstalled then
  266.    begin
  267.      Result := '';
  268.      Exit;
  269.    end;
  270.    Reg := TRegistry.Create;
  271.    Reg.RootKey := HKEY_LOCAL_MACHINE;
  272.    Reg.OpenKey('SOFTWARE/Microsoft/MSSQLServer/Setup'true);
  273.    Path := Reg.ReadString('SQLPath');
  274.    Result := Path + '/Data/';
  275.    Reg.CloseKey;
  276.    Reg.Free;
  277. end;
  278. /// <summary>
  279. /// do operations order with commandstr
  280. /// </summary>
  281. /// <param name="CommandStr">command line</param>
  282. procedure SQLServicesOperation(CommandStr: string);
  283. var
  284.    sCommandLine       : string;
  285.    bCreateProcess     : Boolean;
  286.    lpStartupInfo      : TStartupInfo;
  287.    lpProcessInformation: TProcessInformation;
  288. begin
  289.    sCommandLine := CommandStr;
  290.    // fill record space
  291.    FillChar(lpStartupInfo, SizeOf(TStartupInfo), #0);
  292.    lpStartupInfo.cb := SizeOf(TStartupInfo);
  293.    lpStartupInfo.dwFlags := STARTF_USESHOWWINDOW;
  294.    lpStartupInfo.wShowWindow := SW_HIDE;
  295.    // create process
  296.    bCreateProcess := CreateProcess(nil, PChar(sCommandLine), nilniltrue,
  297.      CREATE_NEW_CONSOLE or NORMAL_PRIORITY_CLASS, nilnil, lpStartupInfo,
  298.      lpProcessInformation);
  299.    // wait for process finished
  300.    if bCreateProcess then
  301.      WaitForSingleObject(lpProcessInformation.hProcess, INFINITE);
  302. end;
  303. function GetSQLServerDataRoot:string;
  304. var
  305.    Reg                : TRegistry;
  306.    Path               : string;
  307. begin
  308.    if not SQLServerInstalled then
  309.    begin
  310.      Result := '';
  311.      Exit;
  312.    end;
  313.    Reg := TRegistry.Create;
  314.    Reg.RootKey := HKEY_LOCAL_MACHINE;
  315.    Reg.OpenKey('SOFTWARE/Microsoft/MSSQLServer/Setup'true);
  316.    Path := Reg.ReadString('SQLDataRoot');
  317.    Result := Path + '/Data/';
  318.    Reg.CloseKey;
  319.    Reg.Free;
  320. end;  
  321. { TCustomDBBackupRestoreThread }
  322. constructor TCustomSQLBackupThread.Create(CreateSuspended: Boolean);
  323. begin
  324.    inherited Create(CreateSuspended);
  325.    // if you want to get the state when thread finished,
  326.    // add a method of type TNotifyEvent and bind it to:
  327.    // OnTerminate event of this class.
  328. end;
  329. procedure TCustomSQLBackupThread.Execute;
  330. var
  331.    Qry                : TADOQuery;
  332. begin
  333.    Qry := TADOQuery.Create(nil);
  334.    with Qry do
  335.    begin
  336.      ConnectionString := Format(ConnStr,
  337.        [DBHost, UserID, UserPwd, DatabaseName]);
  338.      SQL.Text := Format(BackupStr, [DatabaseName, BackupFileName]);
  339.      try
  340.        ExecSQL;
  341.        FBackupState := ssSuccess;
  342.        FErrorMessage := '';
  343.      except
  344.        on E: Exception do
  345.        begin
  346.          FBackupState := ssFail;
  347.          FErrorMessage := E.Message;
  348.        end;
  349.      end;
  350.      Free;
  351.    end;
  352.    if Assigned(onFinish) then
  353.      OnFinish(Self);
  354. end;
  355. { TCustomSQLRestoreThread }
  356. constructor TCustomSQLRestoreThread.Create(CreateSuspended: Boolean);
  357. begin
  358.    inherited Create(CreateSuspended);
  359.    // if you want to get the state when thread finished,
  360.    // add a method of type TNotifyEvent and bind it to:
  361.    // OnTerminate event of this class.
  362. end;
  363. procedure TCustomSQLRestoreThread.Execute;
  364. var
  365.    Qry                : TADOQuery;
  366.    phyData:string;
  367.    phyLog:string;
  368. begin
  369.    // Stop SQL Server Services
  370.    // this operation may let all user connects logoff.
  371.    SQLServicesOperation('net stop MSSQLSERVER');
  372.    // restart SQL Server
  373.    SQLServicesOperation('net start MSSQLSERVER');
  374.    // Restore database
  375.    Qry := TADOQuery.Create(nil);
  376.    with Qry do
  377.    begin
  378.      // if you want to restore "master"
  379.      // change "master" to other Database's name
  380.      phyData := GetSQLServerDataRoot+LogicDatabaseName;
  381.      phyLog := GetSQLServerDataRoot+LogicLogName;
  382.      ConnectionString := Format(ConnStr,
  383.        [DBHost, UserID, UserPwd, 'master']);
  384.      SQL.Text := Format(RestoreStr,
  385.        [DatabaseName, BackupFileName, LogicDatabaseName, phyData,
  386.          LogicLogName, phyLog]);
  387.      try
  388.        ExecSQL;
  389.        FBackupState := ssSuccess;
  390.        FErrorMessage := '';
  391.      except
  392.        SQL.Text := Format(RestoreStr2, [DatabaseName, BackupFileName]);
  393.        try
  394.          ExecSQL;
  395.          FBackupState := ssSuccess;
  396.          FErrorMessage := '';
  397.        except
  398.          on E: Exception do
  399.          begin
  400.            FBackupState := ssFail;
  401.            FErrorMessage := E.Message;
  402.          end;
  403.        end;
  404.      end;
  405.      Free;
  406.    end;
  407.    if Assigned(onFinish) then
  408.      OnFinish(Self);
  409. end;
  410. end.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Pro SQL Server Wait Statistics is a practical guide for analyzing and troubleshooting SQL Server performance using wait statistics. Whether you are new to wait statistics, or already familiar with them, this book will help you gain a deeper understanding of how wait statistics are generated and what they can mean for your SQL Server’s performance. Besides the most common wait types, Pro SQL Server Wait Statistics goes further into the more complex and performance threatening wait types. The different wait types are categorized by their area of impact, and include CPU, IO, Lock, and many more different wait type categories. Filled with clear examples, Pro SQL Server Wait Statistics helps you gain practical knowledge of why and how specific wait times increase or decrease, and how they impact your SQL Server’s performance. What you’ll learn How wait Statistics are generated by SQL Server Script examples for analyzing and tuning wait statistics How to lower, or even eliminate, wait times that hurt performance How to query wait statistics information from Dynamic Management Views How to build reliable and solid wait statistics baselines from which to detect performance issues Who this book is for Pro SQL Server Wait Statistics is the perfect guide for SQL Server DBAs wanting to troubleshoot and optimize SQL Server database installations. The book is also of interest to database developers who are serious about developing highly-performant applications and reporting systems. Table of Contents Part I: Foundations of Wait Statistics Analysis 23 Chapter 1: Wait Statistics Internals Chapter 2: Querying SQL Server Wait Statistics Chapter 3: Building a Solid Baseline Part II: Wait Types Chapter 4: CPU-Related Wait Types Chapter 5: IO-Related Wait Types Chapter 6: Backup-Related Wait Types Chapter 7: Lock-Related Wait Types Chapter 8: Latch-Related Wait Types Chapter 9: High-Availability and Disaster-Recovery Wait Types Chapter 10: Preemptive Wait Types Chapter 11: Background and Miscellaneous Wait Types Chapter 12: In-Memory OLTP–Related Wait Types Appendix I: Example SQL Server Machine Configurations Appendix II: Spinlocks Appendix III: Latch Classes

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值