views:

38

answers:

2

Hi, I have a multithread server that uses one MSSQL which each client should have access to. I wanted to use connection pooling also I am using this:

public static void DBconn()
        {
                SqlConnection pripojeni = new SqlConnection();
                pripojeni.ConnectionString = "Data Source=localhost\\SQLEXPRESS;Initial Catalog=XYZ;Trusted_Connection=True;Min Pool Size=20";

        }

Does the object will persist in memory (not the object itself rather than the open connections) if connection strings states "min pool"? Or will it be gone after finishing this method? Thanks

+4  A: 

You should use a new SqlConnection object for each connection, not create one in the static constructor. Connection Pooling works when each connection you create uses the same connection string (you should store it in a configuration file like web.config or app.config).

Just create and open a SqlConnection object each time, remember to close/dispose it at the end, and connection pooling will ensure that it re-uses existing, open connections.

Hope that helps!

Kieren Johnstone
There is no constructor involved in the OP code sample (you can tell from the `public` keyword).
Fredrik Mörk
A: 

Since you newly declared the SqlConnection object in this method it will be gone after the method ends.

try this for a continued connection:

public static class PerstistendDB
    {
        // Readonly so it can't be destroyed!
        public static readonly System.Data.SqlClient.SqlConnection pripojeni = new System.Data.SqlClient.SqlConnection(
            "Data Source=localhost\\SQLEXPRESS;Initial Catalog=XYZ;Trusted_Connection=True;Min Pool Size=20");
    }

Note: I agree with Kieren, if you keep your connection open at all time, you will clog the database, it's (almost always) much better to open and close each time.

MrFox
But so far I experienced little "lags" when new connection is being established :(
Tomas
Connection pooling will keep connections open anyway, but using one SqlConnection object in a multithreaded application will not work I'm afraid
Kieren Johnstone
Hi Tomas, connection pooling means you should not get this lag. You still should create and use a new connection object each time, or for each group of queries.
Kieren Johnstone
Open connections can be closed by network errors etc. Using a static connection would be very error prone. Another case to not use static connections is transactions.
jgauffin
Never it's a good solutions, but it answers his question.
MrFox