【问题标题】:Why is Sql Server database busy?为什么 Sql Server 数据库很忙?
【发布时间】:2014-07-08 17:28:18
【问题描述】:

我正在尝试创建一个数据库,对其运行一些测试,然后删除该数据库:

namespace TestConsole
{
    class Program
    {
        static void Main(string[] args)
        {
            const string testConnectionString = @"Server=localhost\SQL2014EXPRESS64; Database=RepoTest; Trusted_Connection=True;";
            const string masterConnectionString = @"Server=localhost\SQL2014EXPRESS64; Database=master; Trusted_Connection=True;";

            // connect to master and create RepoTest db
            using (var connection = new SqlConnection(masterConnectionString))
            using (var command = new SqlCommand("CREATE DATABASE RepoTest", connection))
            {
                connection.Open();
                command.ExecuteNonQuery();
            }

            // connect to RepoTest and create some new tables
            using (var connection = new SqlConnection(testConnectionString))
            using (var command = new SqlCommand("CREATE TABLE Test(ID INT NOT NULL)", connection))
            {
                connection.Open();
                command.ExecuteNonQuery();
            }

            // connect to master and delete RepoTest db
            using (var connection = new SqlConnection(masterConnectionString))
            using (var command = new SqlCommand("DROP DATABASE RepoTest", connection))
            {
                connection.Open();
                command.ExecuteNonQuery();
            }
        }
    }
}

但我在尝试删除测试数据库时收到此异常:

System.Data.dll 中出现“System.Data.SqlClient.SqlException”类型的未处理异常
附加信息:无法删除数据库“RepoTest”,因为它当前正在使用中。

但我希望它不再被使用,因为使用该数据库的部分位于 using 块中,所以我希望连接关闭并且操作完成,如果不是这种情况存在当数据库完成当前进程时,我可以使用一个命令来删除数据库吗?

【问题讨论】:

  • 只是为了好玩和咯咯笑,在第三部分之前加上Thread.Sleep(1000)
  • 看看herehere 了解一些想法。
  • 尝试将pooling=false 添加到您的连接字符串以禁用连接池。
  • 您是否考虑过在tempdb 中创建表和其他对象?

标签: c# sql-server


【解决方案1】:

您使用 testConnectionString 的连接对象将使用池。
通过添加 Pooling=false 禁用该连接字符串上的池:

const string testConnectionString = @"Server=.; Database=RepoTest; Trusted_Connection=True;Pooling=false;";

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-20
    相关资源
    最近更新 更多