首页 > 编程 > .NET > 正文

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

2024-07-10 13:13:04
字体:
来源:转载
供稿:网友

首先我们先分析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();
}

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表