通过C#删除SQL Server数据库

Ans*_*tia 12 .net c# sql-server-2008

我正在使用此代码通过C#删除数据库

Int32 result = 0;

try
{
        String Connectionstring = CCMMUtility.CreateConnectionString(false, txt_DbDataSource.Text, "master", "sa", "happytimes", 1000);

        SqlConnection con = new SqlConnection();
        con.ConnectionString = Connectionstring;

        String sqlCommandText = "DROP DATABASE [" + DbName + "]";
        if (con.State == ConnectionState.Closed)
        {
            con.Open();
            SqlConnection.ClearPool(con);
            con.ChangeDatabase("master");
            SqlCommand sqlCommand = new SqlCommand(sqlCommandText, con);
            sqlCommand.ExecuteNonQuery();
        }
        else
        {
            con.ChangeDatabase("master");
            SqlCommand sqlCommand = new SqlCommand(sqlCommandText, con);
            sqlCommand.ExecuteNonQuery();
        }



        con.Close();
        con.Dispose();
        result = 1;
    }
    catch (Exception ex)
    {
        result = 0;
    }
    return result;
Run Code Online (Sandbox Code Playgroud)

但是我收到了一个错误

数据库目前正在使用中

有人可以帮忙吗?

Bas*_*sem 24

以下是使用Entity Framework第6版的方法

System.Data.Entity.Database.Delete(connectionString);
Run Code Online (Sandbox Code Playgroud)


Dav*_*kle 22

试试这个:

String sqlCommandText = @"
ALTER DATABASE " + DbName + @" SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
DROP DATABASE [" + DbName + "]";
Run Code Online (Sandbox Code Playgroud)

还要确保您的连接字符串默认为master数据库,或者您正在删除的数据库以外的任何其他数据库!

顺便说一句,你真的不需要围绕你的查询所有这些东西.ConnectionState将始终启动Closed,因此您无需检查.同样,将连接包装在using块中,无需显式关闭或处置连接.你真正需要做的就是:

String Connectionstring = CCMMUtility.CreateConnectionString(false, txt_DbDataSource.Text, "master", "sa", "happytimes", 1000);

using(SqlConnection con = new SqlConnection(Connectionstring)) {
    con.Open();
    String sqlCommandText = @"
        ALTER DATABASE " + DbName + @" SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
        DROP DATABASE [" + DbName + "]";
    SqlCommand sqlCommand = new SqlCommand(sqlCommandText, con);
    sqlCommand.ExecuteNonQuery();
}
result = 1;
Run Code Online (Sandbox Code Playgroud)