• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

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

asp 搞代码 4年前 (2022-01-03) 41次浏览 已收录 0个评论

因为数据库正在使用,所以未能获得对数据库的排它访问权?

这个问题困惑我好长的时间,在网上搜,也没完全的解决方案,不是过于简单,就是乱说,有的论坛上还没人回答这个问题.今天我彻底解决这个问题,并在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)
{
str来源gao@daima#com搞(%代@#码网ing 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

以上就是asp.net 因为数据库正在使用的解决方法的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:asp.net 因为数据库正在使用的解决方法

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址