我想对SQL数据库做备份还原,我应该怎么用代码实现,,,,,,请给个源码,本人新手,先谢谢了,请各位大侠帮个忙.............

解决方案 »

  1.   

    用sql语句backup 'RESTORE 等,也可以用sql server中的存储过程
    下面的例子是我贴来的,不知道能不能用,不过大概可以起个引导作用。procedure TBak.btnRestoreClick(Sender: TObject);
    var
      Qry:TADOQuery;
    begin
      if FileExists(self.edtReStorePath.Text) then
        begin
          DM.Conn.Connected:=False; //断开系统数据库连接
          Qry:=TADOQuery.Create(self);
          Qry.CommandTimeout:=120;
          //把连接转移到master库
          Qry.ConnectionString:='Provider=SQLOLEDB.1;Password='+Login.GetDBServerInfo('Pwd')+';Persist Security Info=True;User ID='+Login.GetDBServerInfo('User')+';Initial Catalog=master;Data Source='+Login.GetDBServerInfo('Server');
          //-------------------端开rxd_CRM库------------------------------------------
          Qry.Close;
          Qry.SQL.Clear;
          Qry.SQL.Text:='ALTER DATABASE rxd_CRM SET OFFLINE WITH ROLLBACK IMMEDIATE';
          Qry.Prepared;
          Qry.ExecSQL;
          //------------------- 端开rxd_CRM库结束-------------------------------------
          Qry.Close;
          Qry.SQL.Clear;
          Qry.SQL.Text:='RESTORE DATABASE rxd_CRM FROM DISK='''+self.edtReStorePath.Text+''' with replace';
          Qry.Prepared;
          try
            Qry.ExecSQL;
            Login.MsgInfo('成功恢复数据!');
          finally
            //-------------------重新连接rxd_CRM库------------------------------------
            Qry.Close;
            Qry.SQL.Clear;
            Qry.SQL.Text:='ALTER DATABASE rxd_CRM SET ONLINE WITH ROLLBACK IMMEDIATE';
            Qry.Prepared;
            Qry.ExecSQL;
            //-------------------重新连接rxd_CRM库结束--------------------------------
            Qry.Free;
            DM.Conn.ConnectionString:=Login.GetDBServerInfo('DBStr');
            try
              DM.Conn.Connected:=True;
            except
              Login.MsgError('连接数据库失败,请尝试重启系统!');
            end;
          end
        end
      else
        begin
          Login.MsgInfo('数据文件不存在,请重新选择!');
          self.edtReStorePath.SetFocus;
        end;
    end;