2

We have a web server which connects to a database using a single connection string, which makes it a strong candidate for being able to use a Connection Pool.

Do we need one SqlConnection object, or many?

i.e. Should we set up one connection in shared memory, and use that each time, or should we create a new one each time we want to use any connection object?

Is it the call to .Open() which assigns it from a pool, or the creating of a new object with the same connection string?

Also, do we need to call .Close() on the connection before it's released back into the pool, or is the variable going out of scope enough?

I read somewhere (I forget where exactly - sorry) that you shouldn't call close on connections in a pool, because it removes them from the pool somehow.

4

2 回答 2

4

值得记住的是,相同的连接字符串将重新使用已返回到池中的连接,但以任何方式更改它都会导致与服务器建立新的连接。

即假设 SQLBox 的 IP 为 10.0.0.1

using (var conn = new SqlConnection(@"Server=10.0.0.1;...") {
                conn.Open();
                .. Do work ..
                conn.Close();
}
using (var conn = new SqlConnection(@"Server=SQLBox;…") {
                conn.Open(); // This will *NOT* reuse the connection from the pool.
                .. Do work ..
                conn.Close();
}
using (var conn = new SqlConnection(@"Server=10.0.0.1;...") {
                conn.Open(); // This *WILL* reuse the connection from the pool.
                .. Do work ..
                conn.Close();
}
于 2014-12-15T15:37:40.513 回答
1

每次需要访问数据库时都应打开一个单独的连接,并在完成所有访问后关闭它。不要让您的连接打开太久。这不是必需的,现代数据库绝对非常擅长处理多个连接。

您可以将连接池的管理留给 SQL Server - 只要您不试图阻止它,它就会做得很好。

最好使用本地连接对象,而不是在代码的多个部分共享它。您可以使用using模式来确保您的连接将被关闭:

using (SqlConnection conn = new SqlConnection("connectionstring"))
{
    conn.Open();
    // use your connection here
}
于 2013-10-17T12:10:33.263 回答