【发布时间】:2015-02-24 23:40:29
【问题描述】:
我理解从应用程序连接到 sql server 时使用 using 块的概念,因为它会在连接超出范围时立即关闭连接,从而节省我们编写 try catch finally 块的时间。
但我的问题是,在初始化 SqlCommand 时使用 using 有什么好处吗?通常我会这样做:
string cs = ConfigurationManager.ConnectionStrings["CS1"].ConnectionString;
using(SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("SELECT * FROM dbo.City", con);
con.Open();
DropDownList1.DataSource = cmd.ExecuteReader();
DropDownList1.DataTextField = "City";
DropDownList1.DataValueField = "ID";
DropDownList1.DataBind();
}
但是,通过将 SqlCommand 初始化放入 using block,我可以获得哪些可能的好处?
string cs = ConfigurationManager.ConnectionStrings["CS1"].ConnectionString;
using(SqlConnection con = new SqlConnection(cs))
{
using(SqlCommand cmd = new SqlCommand("SELECT * FROM dbo.City", con))
{
con.Open();
DropDownList1.DataSource = cmd.ExecuteReader();
DropDownList1.DataTextField = "City";
DropDownList1.DataValueField = "ID";
DropDownList1.DataBind();
}
}
我在网上搜索的所有材料都谈到了连接一旦超出范围就会关闭,是的,我明白这一点,但是将 SqlCommand 放在 using 块中会不会提高效率?
非常感谢任何建议或指示,谢谢。
【问题讨论】:
标签: c# asp.net .net sql-server .net-4.5