如何使用ASP.NET备份和恢复SqlServer数据库

作者:网络 来源:佚名 更新时间:2008-12-21 15:01:38 点击:

首先我们先分析asp备份sql数据库的代码,详细如下:

备份sqlserver数据库:
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();
}

下面是asp.net还原sql数据库的方法,代码如下:

还原sqlserver数据库:
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();
}