我应该在何时打开和关闭到SQL Server的连接 [英] When should I open and close a connection to SQL Server

查看:136
本文介绍了我应该在何时打开和关闭到SQL Server的连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的静态类的一些方法在里面。每个这些方法打开一个SqlConnection,查询数据库,并关闭连接。这样的话,我相信,我总是关闭连接到数据库,但另一方面,我不喜欢总是打开和关闭连接。下面是什么我的方法看起来像一个例子。

I have a simple static class with a few methods in it. Each of those methods open a SqlConnection, query the database and close the connection. This way, I am sure that I always close the connection to the database, but on the other hand, I don't like to always open and close connection. Below is an example of what my methods look like.

public static void AddSomething(string something)
{
    using (SqlConnection connection = new SqlConnection("..."))
    {
        connection.Open();
        // ...
        connection.Close();
    }
}

考虑到的方法是内部的静态类,我应该有一个包含一个单一的SqlConnection的静态成员?如何及何时我应该放弃它?什么是最好的做法是什么?

Considering that the methods are inside a static class, should I have a static member containing a single SqlConnection? How and when should I drop it? What are the best practices?

推荐答案

没有,不保持静态的SqlConnection ,除非你不得不这样做。线程是一个关注,但更重要的是 - 通常你根本不需要。有了您的code为presented,内部连接池意味着大部分的时间,你会得到连续调用相同的基础连接反正(只要你使用相同的连接字符串)。让波尔做好分内的工作;先不谈code。

No, don't keep a static SqlConnection unless you have to. Threading would be one concern, but more importantly - usually you simply don't need to. With your code as presented, the internal connection pooling means that most of the time you will get the same underlying connection on successive calls anyway (as long as you use the same connection string). Let the pooler do its job; leave the code alone.

这也避免了,当你开始有两个线程......现在每个人都可以在自己的连接做的工作会发生什么的问题;与静态的(假设你不使用 [ThreadStatic] )你必须同步,引入的延迟。更不用说重入(即一个单个线程试图使用相同的连接两次在同一时间)。对;先不谈code。现在是好的,几乎任何你做出的改变将使它不精。

This also avoids the issues of what happens when you start having two threads... now each can do work on their own connection; with static (assuming you don't use [ThreadStatic]) you'd have to synchronize, introducing delays. Not to mention re-entrancy (i.e. a single thread trying to use the same connection twice at the same time). Yup; leave the code alone. It is fine now, and almost any change you make would make it not fine.

这篇关于我应该在何时打开和关闭到SQL Server的连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆