当前位置: 移动技术网 > IT编程>开发语言>.net > asp.net 因为数据库正在使用的解决方法

asp.net 因为数据库正在使用的解决方法

2018年02月25日  | 移动技术网IT编程  | 我要评论

96596,超级演说家 林志颖,先锋军港口

这个问题困惑我好长的时间,在网上搜,也没完全的解决方案,不是过于简单,就是乱说,有的论坛上还没人回答这个问题.今天我彻底解决这个问题,并在c#里测试完全通过.现在把他写出来,希望对朋友们有帮助(如要转载,记得给我版权哦.嘿嘿!!!).以下信息是综合网上的资料和我的实际问题,整理出来的.
备份:
在备份按钮里写:
复制代码 代码如下:

protected void button1_click(object sender, eventargs e)
{
string path = "e:\\maz数据库备份\\" + menu+ ".bak";
if (file.exists(path))
{
file.delete(path);//注意,这个步骤很重要,如果重复,在备份的数据,就会变成,

//你刚开始的数据,所以每次都要先删除.

      }
if (!file.exists(path))
{
filestream fs = file.create(path);

fs.close();
}
string backupstr="backup database test to disk='"+path+"';";
sqlconnection con = new sqlconnection("server=localhost;database=menu;uid=sa;pwd=sa;");
sqlcommand cmd = new sqlcommand(backupstr, con);
try
{
con.open();
cmd.executenonquery();
messagebox.show("备份成功!");
connection.close();

}
catch (exception ex)
{
string stringerror = ex.tostring();
messagebox.show("备份失败!");
connection.close();
}
}

还原:
在还原按钮里写:
复制代码 代码如下:

protected void button2_click(object sender, eventargs e)
{
string path = "e:\\maz数据库备份\\" + menu+ ".bak";


string connectionstringtest = "server=localhost ;database=master;uid=sa;pwd=sa";

sqlconnection connection = new sqlconnection(connectionstringtest);
string backupstr = "restore database menu from disk='" + path + "';";

try
{
string sql = "exec killspid '" + menu+ "'";//这个很关键,要不然就出现题目上的错误了
sqlcommand cmd = new sqlcommand(sql, connection);
connection.open();

cmd.executenonquery();
cmd = new sqlcommand(backupstr, connection);
cmd.executenonquery();
messagebox.show("恢复成功!");
connection.close();
}
catch (exception ex)
{
string stringerror = ex.tostring();
messagebox.show("恢复失败!");
connection.close();
}


}

存储过程 killspid
复制代码 代码如下:

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

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网