问题描述
我正在使用 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 的一个大型打开连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!