Best practice? open and close multi connections, or one large open connection for ado.net(最佳实践?打开和关闭多个连接,或 ado.net 的一个大型打开连接)
问题描述
我正在使用 ADO.Net 进行一些数据库连接,我只是希望我以正确的方式进行操作.我为每个存储过程打开和关闭多个连接.或者我应该把它包装在一个打开的连接中(可能是数据库上的资源更少?)谢谢,如果有什么奇怪的或者我可以做得更好的事情,请告诉我谢谢!
I am using ADO.Net for some database connectivity and I was just hoping I was doing it the right way. I am opening and closing multiple connections for each stored procedure. Or should I be wrapping this up in just one open connection (less resource on the database maybe?) thanks, and if there is anything odd or something I could be doing better let me know thanks!
示例:这个,但我喜欢其中的 6 个...
Example: this but I have like 6 of them...
using (SqlConnection conn = new SqlConnection(ConnectionString))
{
SqlCommand cmd = new SqlCommand("spSelectAllTrip", conn);
cmd.CommandType = CommandType.StoredProcedure;
conn.Open();
ddlTripTypeA.DataSource = cmd.ExecuteReader();
ddlTripTypeA.DataTextField = "TripType";
ddlTripTypeA.DataValueField = "TripTypeAID";
ddlTripTypeA.DataBind();
}
using (SqlConnection conn = new SqlConnection(ConnectionString))
{
SqlCommand cmd = new SqlCommand("spSelectAllTripB", conn);
cmd.CommandType = CommandType.StoredProcedure;
conn.Open();
ddlTripTypeB.DataSource = cmd.ExecuteReader();
ddlTripTypeB.DataTextField = "TripType";
ddlTripTypeB.DataValueField = "TripTypeBID";
ddlTripTypeB.DataBind();
}
推荐答案
.Net 已经为您管理了连接池,因此您无需担心重用连接,就像使用旧的 asp 一样.我总是打几个小的快速电话,而不是一直打开一个,因为不是一直打开的时间通常都用于通话.您的网站代码也在运行之间做一些事情.
.Net has connection pooling already managed for you so you don't need to worry about reusing connections like you might have with old asp. I always go with several small quick calls vs keeping one open the whole time because not all the time it's open is generally used for calls. You have your site code running doing some things between as well.
现在,如果您要一个接一个地进行 6 次连续调用,那么打开一个并重复使用可能是有意义的.但除此之外,我要坚持你正在做的事情.
Now if you are going to make 6 consecutive calls one after another then it might make sense to open one and reuse. But other than that I say just stick with what you are doing.
您可能想要查看的唯一内容是连接管理器,这样您就不必一遍又一遍地在 .net 中创建连接对象.但这与数据库连接与对象创建无关.
The only thing you might want to look into is a connection manager so that you aren't having to create the connection object in .net over and over again. But that doesn't have anything to do with db connections vs just object creation.
这篇关于最佳实践?打开和关闭多个连接,或 ado.net 的一个大型打开连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:最佳实践?打开和关闭多个连接,或 ado.net 的一个大型打开连接
- CanBeNull和ReSharper-将其用于异步任务? 2022-01-01
- Windows 喜欢在 LINUX 中使用 MONO 进行服务开发? 2022-01-01
- 在 LINQ to SQL 中使用 contains() 2022-01-01
- C# 通过连接字符串检索正确的 DbConnection 对象 2022-01-01
- 使用 rss + c# 2022-01-01
- 为什么 C# 中的堆栈大小正好是 1 MB? 2022-01-01
- 是否可以在 .Net 3.5 中进行通用控件? 2022-01-01
- Azure Active Directory 与 MVC,客户端和资源标识同一 2022-01-01
- 在 C# 中异步处理项目队列 2022-01-01
- 带问号的 nvarchar 列结果 2022-01-01