tags:

views:

27

answers:

1

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 clearing the failed connection, I had to clear all...

A: 

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?

VladV
Setting Pooling=false solved the problem! I verified it back and forth a couple of times. Ok so the connection wasnt closed but reused even though it failed to open... seems like an unwanted behaviour? I guess I still want pooling for all other cases. Maybee I can clear the pool if an exception occurs perhaps...
Andreas Zita
I believe, it is a bug. Probably this bug report is related to your issue: https://connect.microsoft.com/VisualStudio/feedback/details/522506/. As a workaround, clearing connection pool on error seems a good idea (note that there is also ClearPool method, that clears the pool for specific connection only).
VladV