开发者

Is SqlConnection-exceptions cached? Im getting the same exception even though changes have been made in between

Consider this code (Yes its ugly but it should also work):

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.
    // ...
}

If I remove the inital check that throws the first exception it will work and it will not throw the second exception. Why do I get this behaviour? Its almost as if the first exception is being remembered/cached for this connectionstring until the second time. But the database has been created (Ive verified that of course) in between so it shouldnt...

Update:

The problem was connection-pooling as ValdV suggested. Ive changed the code above to the following and it now works:

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

Somehow it didnt work just clear开发者_JS百科ing the failed connection, I had to clear all...


Well, probably the only cache that might have some influence here is SQL сonnection pool (the connection is not actually closed, it is returned to the pool and reused later).
You could add "Pooling=false" to the connection string to disable it, and see whether anything changes.

Though, I'd suppose that a problem with pooling is unlikely, and there're more chances that you have mistaken somewhere. What is the exact message for both exceptions? Are you sure that database was actually created?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜