通过C#删除SQL Server数据库数据库、SQL、Server

2023-09-04 22:41:15 作者:孤傲

我用这code删除通过C#

I am using this code to delete a database through 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;

不过,我得到一个错误

But I get an error

数据库当前正在使用的

谁能帮助?

推荐答案

试试这个:

String sqlCommandText = @"
ALTER DATABASE " + DbName + @" SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
DROP DATABASE [" + DbName + "]";

此外确保您的连接字符串默认你的数据库或任何其他数据库比您正在下降的另外一个!

Also make sure that your connection string defaults you to the master database, or any other database other than the one you're dropping!

顺便说一句,你真的不需要所有的东西在你的查询。该ConnectionState总会开始关闭,这样你就不会需要检查的。同样,包装使用块在您的连接,无需显式地关闭或释放该连接。你真正需要做的是:

As an aside, you really don't need all of that stuff around your queries. The ConnectionState will always start off Closed, so you don't need to check for that. Likewise, wrapping your connection in a using block eliminates the need to explicitly close or dispose the connection. All you really need to do is:

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;