是否缓存了SqlConnection-exceptions?即使在两者之间进行了更改,我也会得到相同的异常

时间:2010-10-16 11:47:31

标签: c# sql ado.net

考虑这段代码(是的,它的丑陋,但也应该有效):

try
{
    // Test the connection to a database that does not exist yet...
    using (SqlConnection c = new SqlConnection("Data Source=localhost;Initial Catalog=test;Integrated Security=True"))
    {
        c.Open();
    } // Dispose calls Close()
}
catch
{
    //... will fail with an exception
}

// Creating the database...
using (SqlConnection c = new SqlConnection("Data Source=localhost;Integrated Security=True"))
{
    c.Open();
    SqlCommand cmd = new SqlCommand("CREATE DATABASE test", c);
    cmd.ExecuteNonQuery();
}

using (SqlConnection c = new SqlConnection("Data Source=localhost;Initial Catalog=test;Integrated Security=True"))
{
    c.Open(); // Failes with the same exception even though the database have been created in between.
    // ...
}

如果我删除了抛出第一个异常的初始检查,它将起作用,它不会抛出第二个异常。为什么我会这样做?它几乎就像第一次异常被记住/缓存这个连接字符串直到第二次。但是数据库已经创建(我当然已经验证过),所以它不应该......

更新

问题是ValdV建议的连接池。我已将上面的代码更改为以下代码,现在可以正常运行:

try
{
    using (SqlConnection c = new SqlConnection(cstr))
    {
        c.Open();
    }
}
catch
{
    SqlConnection.ClearAllPools(); // clear all pooled connections
}

不知怎的,它只是清除失败的连接,我不得不清除所有......

1 个答案:

答案 0 :(得分:0)

好吧,可能这里唯一可能产生影响的缓存是SQLсonnection池(连接实际上没有关闭,它会返回池并稍后重用)。
您可以在连接字符串中添加“Pooling = false”以禁用它,并查看是否有任何更改。

尽管如此,我认为合并的问题不太可能,并且你有更多机会误认为某处。两个例外的确切消息是什么?你确定数据库是真的创建的吗?

相关问题