我目前有以下命令SqlCommand command = new SqlCommand(@sys.sp_detach_db DBname, conn);分离数据库,但它在执行时抛出异常.说数据库正在使用中.如何在分离时或之前断开连接?更新:我目前正在使用SMO,但它仍然...

我目前有以下命令
SqlCommand command = new SqlCommand(@"sys.sp_detach_db 'DBname'", conn);
分离数据库,但它在执行时抛出异常.说数据库正在使用中.如何在分离时或之前断开连接?
更新:
我目前正在使用SMO,但它仍然无法正常工作:
bool DetachBackup(string backupDBName)
{
string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
var builder = new SqlConnectionStringBuilder(connectionString);
string serverName = builder.DataSource;
string dbName = builder.InitialCatalog;
try
{
Server smoServer = new Server(serverName);
smoServer.DetachDatabase(backupDBName + DateTime.Now.ToString("yyyyMMdd"), false);
return true;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
return false;
}
}
解决方法:
你可以使用SMO
Detaches the specified database from the instance of SQL Server with
the option to update statistics before the database is detached.
using Microsoft.SqlServer.Management.Smo;
void DetachDatabase()
{
Server smoServer = new Server("MSSQLSERVER2008");
smoServer.DetachDatabase("Yourdatabasename", False);
}
要从app.config获取服务器名称,您可以尝试这样:
string connectString = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(connectString);
string serverName = builder.DataSource; //Server name
string dbName = builder.InitialCatalog; //Database name
织梦狗教程
本文标题为:C#分离数据库时如何断开连接


基础教程推荐
猜你喜欢
- C#中使用Spire.XLS来操作Excel数据的实现 2023-07-18
- c# – Linq-To-SQL中的黑客新闻样式排序算法 2023-11-10
- C# SQLite库使用技巧 2023-05-11
- C# Socket通信的实现(同时监听多客户端) 2023-04-14
- 详解c# 中的DateTime 2023-03-04
- 基于Unity Line Renderer组件的常用属性说明 2023-04-10
- c#使用Aspose打印文件的示例 2023-04-14
- C#中通过LRU实现通用高效的超时连接探测 2023-01-06
- C#利用GDI+给图片添加文字(文字自适应矩形区域) 2022-12-14
- C#中RSA加密与解密的实例详解 2023-01-27