C#分离数据库时如何断开连接

我目前有以下命令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#分离数据库时如何断开连接

基础教程推荐