petshop的代码中一个叫DBUlitily的类非常有用,其中有这么一个方法: public static SqlDataReader ExecuteReader(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters) {
SqlCommand cmd = new SqlCommand();
SqlConnection conn = new SqlConnection(connectionString); // we use a try/catch here because if the method throws an exception we want to
// close the connection throw code, because no datareader will exist, hence the
// commandBehaviour.CloseConnection will not work
try {
PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
cmd.Parameters.Clear();
return rdr;
}
catch {
conn.Close();
throw;
}
}根据注释的那段话,在方法ExecuteReader调用正常结束时,其间定义的SqlConnection对象conn是不会执行close的。再看一下其他类对ExecuteReader的调用:在PetShop.SQLServerDAL.Item类中,有这么一个方法: public IList<ItemInfo> GetItemsByProduct(string productId) { ……………… using(SqlDataReader rdr = SqlHelper.ExecuteReader(SqlHelper.ConnectionStringLocalTransaction, CommandType.Text, SQL_SELECT_ITEMS_BY_PRODUCT, parm)) {
// Scroll through the results
while (rdr.Read()) {
ItemInfo item = new ItemInfo(rdr.GetString(0), rdr.GetString(1), rdr.GetInt32(2), rdr.GetDecimal(3), rdr.GetString(4), rdr.GetString(5), rdr.GetString(6), rdr.GetString(7));
//Add each item to the arraylist
itemsByProduct.Add(item);
}
}
return itemsByProduct;
}同样的,当reader对象被dispose后,其连接依旧没有关闭。请问这是petshop的疏忽之处还是另有目的?
SqlCommand cmd = new SqlCommand();
SqlConnection conn = new SqlConnection(connectionString); // we use a try/catch here because if the method throws an exception we want to
// close the connection throw code, because no datareader will exist, hence the
// commandBehaviour.CloseConnection will not work
try {
PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
cmd.Parameters.Clear();
return rdr;
}
catch {
conn.Close();
throw;
}
}根据注释的那段话,在方法ExecuteReader调用正常结束时,其间定义的SqlConnection对象conn是不会执行close的。再看一下其他类对ExecuteReader的调用:在PetShop.SQLServerDAL.Item类中,有这么一个方法: public IList<ItemInfo> GetItemsByProduct(string productId) { ……………… using(SqlDataReader rdr = SqlHelper.ExecuteReader(SqlHelper.ConnectionStringLocalTransaction, CommandType.Text, SQL_SELECT_ITEMS_BY_PRODUCT, parm)) {
// Scroll through the results
while (rdr.Read()) {
ItemInfo item = new ItemInfo(rdr.GetString(0), rdr.GetString(1), rdr.GetInt32(2), rdr.GetDecimal(3), rdr.GetString(4), rdr.GetString(5), rdr.GetString(6), rdr.GetString(7));
//Add each item to the arraylist
itemsByProduct.Add(item);
}
}
return itemsByProduct;
}同样的,当reader对象被dispose后,其连接依旧没有关闭。请问这是petshop的疏忽之处还是另有目的?
SqlDataReader 关闭时回关闭Connection
*****************************************************************************
欢迎使用CSDN论坛专用阅读器 : CSDN Reader(附全部源代码) 最新版本:20070212http://www.cnblogs.com/feiyun0112/archive/2006/09/20/509783.html