首页 > 代码库 > SQL Server 数据库还原

SQL Server 数据库还原

---恢复内容开始---

  对于一个优秀的应用程序来说,具有数据恢复功能尤为重要。因为数据恢复功能可以在数据找到破坏时,将数据恢复到系统中,保证系统重新正常运转,从而避免因数据找到异常丢失所带来的损失。本实例将演示怎样在C#中还原数据库。

  还原数据库是使用数据库的备份文件对数据库进行还原操作。由于病毒的破坏、磁盘损坏或操作失误等原因会导致数据丢失、不完整或数据错误,此时,需要对数据库进行还原,将数据还原到某一天,前提是必须存在数据备份。

  SQL Server数据库恢复支持4种类型,分别应用于不同的场合,下面进行简要介绍。

  (1)还原整个数据库的完整数据库还原。

  (2)完整数据库还原和差异数据库还原。通过使用RESTORE DATABASE语句还原差异备份。

  (3)事务日志还原。

  (4)个别文件和文件组还原。文件和文件组的还原既可以通过文件或文件组备份操作完成,也可以通过完整数据库备份操作完成。在还原文件或文件组时,必须应用事务日志。此外,文件差异备份可以在完成完整文件还原后还原。

注意:还原数据库备份将重新创建数据库和备份完成时数据库中存在的所有相关文件。但是,自创建备份文件后所做的任何数据库修改丢将丢失。若要还原创建数据库备份后所发生的事务,必须使用事务日志备份或差异备份。

本实例运用SQLDMO.Restore对象还原使用BACKUP命令所做的整个数据库备份。

RESTORE的语法格式如下:

RESTORE DATABASE{database_name|@database_name_var} [FROM<backup_device>[,...n]][WITH    [RESTRICTED_USER]    [[,]FILE={file_number|@file_number}]    [[,]PASSWORD={password|@password_variable}]    [[,]MEDIANAME={media_name|@media_name_variable}]    [[,]MEDIAPASSWORD={mediapassword|@mediapassword_variable}]    [[,]MOVE logical_file_name TO operating_system_file_name]        [,...n]    [[,]KEEP_REPLICATION]    [[,]{NORECOVERY|RECOVERY|STANDBY=undo_file_name}]     [[,]{NOREWIND|REWIND}]    [[,]{NOUNLOAD|UNLOAD}]    [[,]REPLACE]    [[,]RESTART]    [[,]STATS[=percentage]] ]
View Code

还原数据库参数及说明如下:

还原数据库参数及说明
参  数说  明
DATABASE指定从备份还原整个数据库。如果指定了文件盒文件组列表,则只还原那些文件和文件组
{database_name|@database_name_var}是将日志或整个数据库还原到的数据库。如果将其作为变量(@database_name_var)提供,则可将该名称指定为字符串常量(@database_name_var=database name)或字符串数据类型(ntext或text数据类型除外)的变量
FROM

指定从中还原备份的备份设备。如果没有指定FROM子句,则不会发生备份还原,而是恢复数据库。可用省略FROM子句的办法尝试恢复通过NORECOVERY选项还原的数据库,或切换到一台备用服务器上。如果省略FROM子句,则必须指定

NORECOVERY、RECOVERY或STANDBY

 <backup_device>

 指定备份操作时要使用的逻辑或物理备份设备。可以是下列一种或多种形式。

{‘logical_bakcup_device_name‘|@logical_backup_device_name_var}:是由sp_addumpdevice创建的备份设备(数据库将从该备份设备还原)的逻辑名称,该名称必须符合标识符规则。如果作为变量(@logical_backup_device_name_var)

提供,则可以指定字符串常量(@logical_backup_device_name_var=logical_backup_device_name)或字符串数据类型(ntext或text数据类型除外)的变量作为备份设备名。

{DISK|TYPE}=‘physical_backup_device_name‘ @physical_backup_device_name_var:允许从命名磁盘或磁带设备还原备份。磁盘或磁带的设备类型应该用设备的真实名称(如完整的路径和文件名)来指定:DISK=‘C:\Program Files\Microsoft

SQL Server\MSSQL\BACKUP\Mybackup.dat‘ 或TYPE=‘\\.\TAPE0‘。如果指定为变量(@physical_backup_device_name_var),则设备名称可以是字符串常量(@physical_backup_device_name_var = ‘physical_backup_device_name‘)或字

串数据类型(ntext或text数据类型除外)的变量

   本实例主要应用还原数据库的代码如下:

string SqlStr2 = "use master restore database " + dbname + " from disk =‘" + path +"";

 

程序主要代码如下:

Frm_Main.cs:

 1 using System; 2 using System.Collections.Generic; 3 using System.ComponentModel; 4 using System.Data; 5 using System.Drawing; 6 using System.Text; 7 using System.Windows.Forms; 8 using System.Linq; 9 using System.Data.SqlClient;10 11 12 namespace RevertDataBase13 {14     public partial class Frm_Main : Form15     {16         public Frm_Main()17         {18             InitializeComponent();19         }20 21         private void Form1_Load(object sender, EventArgs e)22         {23             using (SqlConnection con = new SqlConnection(//创建数据库连接对象24 @"server=.;pwd=123;uid=sa;database=master"))25             {26                 DataTable dt = new DataTable();//创建数据表27                 SqlDataAdapter da = new SqlDataAdapter(//创建数据适配器28                     "select name from sysdatabases", con);29                 da.Fill(dt);//填充数据表30                 this.cbox_DataBase.DataSource = dt.DefaultView;//设置数据源31                 this.cbox_DataBase.DisplayMember = "name";//设置显示属性32                 this.cbox_DataBase.ValueMember = "name";//设置实际值33             }34         }35 36         private void button2_Click(object sender, EventArgs e)37         {38             if (this.openFileDialog1.ShowDialog() == DialogResult.OK)39             {40                 this.txt_Path.Text = this.openFileDialog1.FileName;//显示备份文件路径信息41             }42         }43 44         private void button1_Click(object sender, EventArgs e)45         {46             Restore();//还原数据库47         }48 49         private void Restore()50         {51             string path = this.txt_Path.Text; //得到备份路径及数据库名称52             string dbname = this.cbox_DataBase.Text;//得到将要还原的数据库名称53             string SqlStr1 = //创建数据库连接字符串54 @"Server=.;database=‘" + this.cbox_DataBase.Text + "‘;Uid=sa;Pwd=123";55             string SqlStr2 =//创建SQL查询语句56                 "use master restore database " + dbname + " from disk=‘" + path + "‘ with replace ";57             using (SqlConnection con = new SqlConnection(SqlStr1))//创建数据库连接对象58             {59                 con.Open();//打开数据库连接60                 try61                 {62                     SqlCommand cmd = new SqlCommand(SqlStr2, con);//创建命令对象63                     cmd.Connection = con;//设置连接属性64                     cmd.ExecuteNonQuery();//执行SQL命令65                     MessageBox.Show("还原数据成功");//弹出消息对话框66                 }67                 catch (Exception ex)68                 {69                     MessageBox.Show(ex.Message,//弹出消息对话框70                         "还原失败,请确保还原项与库对应");71                 }72                 finally73                 {74                     con.Close();//关闭数据库连接75                 }76             }77         }78     }79 }
View Code

Frm_Main.designer.cs:

  1 namespace RevertDataBase  2 {  3     partial class Frm_Main  4     {  5         /// <summary>  6         /// 必需的设计器变量。  7         /// </summary>  8         private System.ComponentModel.IContainer components = null;  9  10         /// <summary> 11         /// 清理所有正在使用的资源。 12         /// </summary> 13         /// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param> 14         protected override void Dispose(bool disposing) 15         { 16             if (disposing && (components != null)) 17             { 18                 components.Dispose(); 19             } 20             base.Dispose(disposing); 21         } 22  23         #region Windows 窗体设计器生成的代码 24  25         /// <summary> 26         /// 设计器支持所需的方法 - 不要 27         /// 使用代码编辑器修改此方法的内容。 28         /// </summary> 29         private void InitializeComponent() 30         { 31             this.label3 = new System.Windows.Forms.Label(); 32             this.txt_Path = new System.Windows.Forms.TextBox(); 33             this.cbox_DataBase = new System.Windows.Forms.ComboBox(); 34             this.label1 = new System.Windows.Forms.Label(); 35             this.btn_Revert = new System.Windows.Forms.Button(); 36             this.btn_path = new System.Windows.Forms.Button(); 37             this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog(); 38             this.SuspendLayout(); 39             //  40             // label3 41             //  42             this.label3.AutoSize = true; 43             this.label3.Location = new System.Drawing.Point(50, 43); 44             this.label3.Name = "label3"; 45             this.label3.Size = new System.Drawing.Size(41, 12); 46             this.label3.TabIndex = 10; 47             this.label3.Text = "路径:"; 48             //  49             // txt_Path 50             //  51             this.txt_Path.Enabled = false; 52             this.txt_Path.Location = new System.Drawing.Point(97, 40); 53             this.txt_Path.Name = "txt_Path"; 54             this.txt_Path.Size = new System.Drawing.Size(172, 21); 55             this.txt_Path.TabIndex = 9; 56             //  57             // cbox_DataBase 58             //  59             this.cbox_DataBase.FormattingEnabled = true; 60             this.cbox_DataBase.Location = new System.Drawing.Point(98, 15); 61             this.cbox_DataBase.Name = "cbox_DataBase"; 62             this.cbox_DataBase.Size = new System.Drawing.Size(171, 20); 63             this.cbox_DataBase.TabIndex = 8; 64             //  65             // label1 66             //  67             this.label1.AutoSize = true; 68             this.label1.Location = new System.Drawing.Point(14, 18); 69             this.label1.Name = "label1"; 70             this.label1.Size = new System.Drawing.Size(77, 12); 71             this.label1.TabIndex = 7; 72             this.label1.Text = "操作数据库:"; 73             //  74             // btn_Revert 75             //  76             this.btn_Revert.Location = new System.Drawing.Point(194, 66); 77             this.btn_Revert.Name = "btn_Revert"; 78             this.btn_Revert.Size = new System.Drawing.Size(75, 23); 79             this.btn_Revert.TabIndex = 6; 80             this.btn_Revert.Text = "恢复"; 81             this.btn_Revert.UseVisualStyleBackColor = true; 82             this.btn_Revert.Click += new System.EventHandler(this.button1_Click); 83             //  84             // btn_path 85             //  86             this.btn_path.Location = new System.Drawing.Point(113, 66); 87             this.btn_path.Name = "btn_path"; 88             this.btn_path.Size = new System.Drawing.Size(75, 23); 89             this.btn_path.TabIndex = 11; 90             this.btn_path.Text = "浏览"; 91             this.btn_path.UseVisualStyleBackColor = true; 92             this.btn_path.Click += new System.EventHandler(this.button2_Click); 93             //  94             // openFileDialog1 95             //  96             this.openFileDialog1.FileName = "openF"; 97             this.openFileDialog1.Filter = "备份文件 (*.bak)|*.bak|所有文件 (*.*)|*.*"; 98             //  99             // Frm_Main100             // 101             this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);102             this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;103             this.ClientSize = new System.Drawing.Size(302, 104);104             this.Controls.Add(this.btn_path);105             this.Controls.Add(this.label3);106             this.Controls.Add(this.txt_Path);107             this.Controls.Add(this.cbox_DataBase);108             this.Controls.Add(this.label1);109             this.Controls.Add(this.btn_Revert);110             this.Name = "Frm_Main";111             this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;112             this.Text = "还原SQL Server数据库";113             this.Load += new System.EventHandler(this.Form1_Load);114             this.ResumeLayout(false);115             this.PerformLayout();116 117         }118 119         #endregion120 121         private System.Windows.Forms.Label label3;122         private System.Windows.Forms.TextBox txt_Path;123         private System.Windows.Forms.ComboBox cbox_DataBase;124         private System.Windows.Forms.Label label1;125         private System.Windows.Forms.Button btn_Revert;126         private System.Windows.Forms.Button btn_path;127         private System.Windows.Forms.OpenFileDialog openFileDialog1;128     }129 }
View Code

源代码:http://dl.vmall.com/c0fj9eivdp