重用SqlConnection的最佳实践 [英] Best practice for reusing SqlConnection

查看:105
本文介绍了重用SqlConnection的最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有Java经验,正在尝试从C#开始。我已阅读 SqlConnection SqlCommand SqlDataReader IDisposable ,并且我可以理解连接到数据库将 SqlConnection SqlCommand SqlDataReader 包装起来使用块。

I've come from Java experience and am trying to start with C#. I've read SqlConnection SqlCommand SqlDataReader IDisposable and I can understand that the best practice to connecting to a DB is wrapping SqlConnection, SqlCommand and SqlDataReader in their own using block.

但是在Java中,我们使用将连接封装到工厂方法中,仅创建一次,并将其重用于所有查询,甚至是多线程查询。仅为每个查询创建语句和结果集,并尽快关闭。

But in Java we use to encapsulate the connection into a factory method, create it only once, and reuse it for all queries, even multithreaded ones. Only statements and result sets are created for each query and closed ASAP.

不为以下内容创建新的 SqlConnection 每个查询有点矫kill过正?不能重用吗?

Isn't creating a new SqlConnection for each query kinda overkill? Can't it be reused?

推荐答案

创建类 SqlConnection 不会创建与SQL Server的新网络连接,而是租用现有连接(或创建一个新连接)。 .NET为您处理物理连接池。

Creating a new instance of the class SqlConnection does not create a new network connection to SQL Server, but leases an existing connection (or creates a new one). .NET handles the physical connection pooling for you.

完成连接(可以通过其发送多个查询)后,只需 Close() Dispose()(或最好使用 using {} 块)。

When you have finished with your connection (through which you can send multiple queries) just Close() or Dispose() (or use a using{} block preferably).

没有必要,也不是很好的做法,来缓存 SqlConnection 类的实例。

There is no need, and not good practise, to cache instances of the SqlConnection class.

这篇关于重用SqlConnection的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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