ASP.NET备份恢复SqlServer数据库

可以采用 SQLDMO 的Backup,Restore 实现,以下介绍的是使用Sql的Backup,Restore来实现:

转自:http://www.enet.com.cn/article/2007/1112/A20071112906795.shtml

备份SqlServer数据库
核心技术:
using System.Data.SqlClient;
using System.IO;
string SqlStr1 = "Server=(local);DataBase=master;Uid=sa;Pwd=";
string SqlStr2 = "Exec sp_helpdb";
string SqlStr1 = "Server=(local);database='" + this.DropDownList1.SelectedValue + "';Uid=sa;Pwd=";
string SqlStr2 = "backup database " + this.DropDownList1.SelectedValue + " to disk='" + this.TextBox1.Text.Trim() + ".bak'";

1.前台

<table>
<tr>
<td style=" 100px"><span style="font-size: 9pt">操 作 数 据 库</span></td>
<td><asp:DropDownList ID="DropDownList1" runat="server" Font-Size="9pt" Width="124px"></asp:DropDownList></td>
<td style=" 100px"></td>
</tr>
<tr>
<td style=" 100px"><span style="font-size: 9pt">备份名称和位置</span></td>
<td style=" 100px"><asp:TextBox ID="TextBox1" runat="server" Font-Size="9pt" Width="117px"></asp:TextBox></td>
<td style=" 100px"><span style="font-size: 9pt; color: #ff3300">(如D:\beifen)</span></td>
</tr>
<tr>
<td colspan="3"><asp:Button ID="Button1" runat="server" Font-Size="9pt" OnClick="Button1_Click" Text="备份数据库" /></td>
</tr>
</table>

2.后台

using System.Data.SqlClient;
using System.IO;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string SqlStr1 = "Server=(local);DataBase=master;Uid=sa;Pwd=";
string SqlStr2 = "Exec sp_helpdb";
SqlConnection con = new SqlConnection(SqlStr1);
con.Open();
SqlCommand com = new SqlCommand(SqlStr2, con);
SqlDataReader dr = com.ExecuteReader();
this.DropDownList1.DataSource = dr;
this.DropDownList1.DataTextField = "name";
this.DropDownList1.DataBind();
dr.Close();
con.Close();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
string SqlStr1 = "Server=(local);database='" + this.DropDownList1.SelectedValue + "';Uid=sa;Pwd=";
string SqlStr2 = "backup database " + this.DropDownList1.SelectedValue + " to disk='" + this.TextBox1.Text.Trim() + ".bak'";
SqlConnection con = new SqlConnection(SqlStr1);
con.Open();
try
{
if (File.Exists(this.TextBox1.Text.Trim()))
{
Response.Write("<script language=javascript>alert('此文件已存在,请从新输入!');location='Default.aspx'</script>");
return;
}
SqlCommand com = new SqlCommand(SqlStr2, con);
com.ExecuteNonQuery();
Response.Write("<script language=javascript>alert('备份数据成功!');location='Default.aspx'</script>");
}
catch (Exception error)
{
Response.Write(error.Message);
Response.Write("<script language=javascript>alert('备份数据失败!')</script>");
}
finally
{
con.Close();
}
}
}



还原SqlServer
核心技术:
string SqlStr1 = "Server=(local);database='" + this.DropDownList1.SelectedValue + "';Uid=sa;Pwd=";
string SqlStr2 = "use master restore database " + dbname + " from disk='" + path + "'";

1.前台
<table>
<tr>
<td style=" 100px; height: 21px"><span style="font-size: 9pt">操 作 数 据 库</span></td>
<td><asp:DropDownList ID="DropDownList1" runat="server" Font-Size="9pt" Width="124px"></asp:DropDownList></td>
<td style=" 100px; height: 21px"></td>
</tr>
<tr>
<td style=" 100px"><span style="font-size: 9pt">操 作 数 据 库</span></td>
<td style=" 100px"><asp:FileUpload ID="FileUpload1" runat="server" Font-Size="9pt" Width="190px" /></td>
<td style=" 100px">
</td>
</tr>
<tr>
<td colspan="3"><asp:Button ID="Button1" runat="server" Font-Size="9pt" OnClick="Button1_Click" Text="还原数据库" /></td>
</tr>
</table>
2.后台

using System.Data.SqlClient;
using System.IO;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string SqlStr1 = "Server=(local);DataBase=master;Uid=sa;Pwd=";
string SqlStr2 = "Exec sp_helpdb";
SqlConnection con = new SqlConnection(SqlStr1);
con.Open();
SqlCommand com = new SqlCommand(SqlStr2, con);
SqlDataReader dr = com.ExecuteReader();
this.DropDownList1.DataSource = dr;
this.DropDownList1.DataTextField = "name";
this.DropDownList1.DataBind();
dr.Close();
con.Close();
}
}

protected void Button1_Click(object sender, EventArgs e)
{
string path = this.FileUpload1.PostedFile.FileName; //获得备份路径及数据库名称
string dbname = this.DropDownList1.SelectedValue;
string SqlStr1 = "Server=(local);database='" + this.DropDownList1.SelectedValue + "';Uid=sa;Pwd=";
string SqlStr2 = "use master restore database " + dbname + " from disk='" + path + "'";
SqlConnection con = new SqlConnection(SqlStr1);
con.Open();
try
{
SqlCommand com = new SqlCommand(SqlStr2, con);
com.ExecuteNonQuery();
Response.Write("<script language=javascript>alert('还原数据成功!');location='Default.aspx'</script>");
}
catch (Exception error)
{
Response.Write(error.Message);
Response.Write("<script language=javascript>alert('还原数据失败!')</script>");
}
finally
{
con.Close();
}
}
}

以下内容转自:http://www.cnblogs.com/windthunder/archive/2009/09/25/1573981.html
在用Asp.net对备份的数据库文件进行还原的时候,有时候会出现下面的错误异常:
[因为数据库正在使用,所以未能获得对数据库的排它访问权。 RESTORE DATABASE 操作异常终止。已将数据库上下文改为 'master'。]
[SQL代码]

--还原数据库时数据库正在使用导致数据库无会还原,此存储过存在msater数据库下创建。exec killspid 'dbname' 结束此数据库的进程,这样才能还原数据库
create proc killspid (@dbname varchar(20))     
as     
begin     
declare @sql   nvarchar(500)     
declare @spid  int     
set @sql='declare getspid cursor for select spid from sysprocesses where dbid=db_id('''+@dbname+''')'     
exec (@sql)     
open getspid     
fetch next from getspid into @spid     
while @@fetch_status <> -1     
begin     
exec('kill '+@spid)     
fetch next from getspid into @spid     
end     
close getspid     
deallocate getspid     
end 


[C#代码]

    /// <summary>
    
/// 恢复数据库,可选择是否可以强制还原(即在其他人在用的时候,依然可以还原)
    
/// </summary>
    
/// <param name="databasename">待还原的数据库名称</param>
    
/// <param name="databasefile">带还原的备份文件的完全路径</param>
    
/// <param name="errormessage">恢复数据库失败的信息</param>
    
/// <param name="forceRestore">是否强制还原(恢复),如果为TRUE,则exec killspid '数据库名' 结束此数据库的进程,这样才能还原数据库</param>
    
/// <returns></returns>
    
public bool RestoreDataBase(string databasename, string databasefile, ref string errormessage,bool forceRestore)
    {
        bool success 
= true;
        string path 
= databasefile;
        string dbname 
= databasename;

        string restoreSql 
= "use master;";

        
if (forceRestore)//如果强制回复
            restoreSql 
+= string.Format("use master exec killspid '{0}';",databasename);

        restoreSql 
+= "restore database @dbname from disk = @path;";

        SqlCommand myCommand 
= new SqlCommand(restoreSql, conn);

        myCommand.Parameters.
Add("@dbname", SqlDbType.Char);
        myCommand.Parameters
["@dbname"].Value = dbname;
        myCommand.Parameters.
Add("@path", SqlDbType.Char);
        myCommand.Parameters
["@path"].Value = path;

        try
        {
            myCommand.Connection.
Open();
            myCommand.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            errormessage 
= ex.Message;
            success 
= false;
        }
        finally
        {
            myCommand.Connection.
Close();
        }

        
return success;
    }


 

原文地址:https://www.cnblogs.com/yangfan/p/1608799.html