c# - 通过 C# 删除 SQL Server 数据库

标签 c# .net 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;

但是我得到一个错误

Database currently in use

有人能帮忙吗?

最佳答案

试试这个:

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

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

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

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;

关于c# - 通过 C# 删除 SQL Server 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14069661/

相关文章:

sql-server - 如何找到SQL Server运行端口?

c# - mahapps 的新手,Datagrids 看起来没有风格

c# - 使用 xamarin.forms 的 iOS 应用程序链接

c# - 可以在浏览器的对话框窗口中模拟点击事件吗?

jquery - 将数组从 js (jQuery) 发送到 sql 存储过程的最佳方法是什么?阵列层间传输

sql-server-2008 - 对数据库的网络服务权限

c# - 将通用类型检查(工厂式模式)改进为更面向 SOLID?

c# - 比较通用列表并过滤不匹配的值

c# - .NET 日期时间解析

c# - 从 64 位应用程序调用 Twain 驱动程序