SqlCommand.Dispose是否关闭连接?
时间:2020-03-05 18:52:51 来源:igfitidea点击:
我可以有效地使用这种方法吗?
using(SqlCommand cmd = new SqlCommand("GetSomething", new SqlConnection(Config.ConnectionString)) { cmd.Connection.Open(); // set up parameters and CommandType to StoredProcedure etc. etc. cmd.ExecuteNonQuery(); }
我的担心是:SqlCommand的Dispose方法(退出using块时会调用)是否关闭基础SqlConnection对象?
解决方案
回答
不,处置SqlCommand不会影响连接。更好的方法是将SqlConnection也包装在using块中:
using (SqlConnection conn = new SqlConnection(connstring)) { conn.Open(); using (SqlCommand cmd = new SqlCommand(cmdstring, conn)) { cmd.ExecuteNonQuery(); } }
否则,由于使用了连接的命令已被处理(也许就是我们想要的?),因此该连接不变。但请记住,连接应该
也要被处置,并且处置可能比命令更重要。
编辑:
我刚刚测试了这个:
SqlConnection conn = new SqlConnection(connstring); conn.Open(); using (SqlCommand cmd = new SqlCommand("select field from table where fieldid = 1", conn)) { Console.WriteLine(cmd.ExecuteScalar().ToString()); } using (SqlCommand cmd = new SqlCommand("select field from table where fieldid = 2", conn)) { Console.WriteLine(cmd.ExecuteScalar().ToString()); } conn.Dispose();
退出using块时,将处理第一个命令。该连接仍处于打开状态,对于第二个命令来说是好的。
因此,处置该命令绝对不会处置其正在使用的连接。
回答
SqlCommand.Dispose是不够的,因为许多SqlCommand可以(重新)使用相同的SqlConnection。将重点放在SqlConnection上。