这是以下代码健康吗?或者我不需要使用using
关键字SqlDataAdapter
来处理关闭连接?
public static DataSet Fetch(string sp, SqlParameter [] prm)
{
using (SqlConnection con = new SqlConnection(ConStr))
{
using (SqlCommand cmd = con.CreateCommand())
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = sp;
cmd.Parameters.AddRange(prm);
using (SqlDataAdapter dta = new SqlDataAdapter(cmd))
{
DataSet dst = new DataSet();
dta.Fill(dst);
return dst;
}
}
}
}
@MarkGravell我在这里需要一个建议,我真的很想使用DataReader
,但我一直在寻找使用using
关键字来确保关闭连接。我们DataReader
不能使用它,因为如果我们想返回DataReader
某个方法,它将关闭连接。那么你认为下面的技术对DataReader
和using
关键字很好:
public static SqlDataReader Fetch(string sp, SqlParameter [] prm)
{
SqlCommand cmd = new SqlConnection(ConStr).CreateCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = sp;
cmd.Parameters.AddRange(prm);
cmd.Connection.Open();
return cmd.ExecuteReader(CommandBehavior.CloseConnection);
}
using (SqlDataReader dtrPrize = Sql.Fetch("SelectPrize", new SqlParameter[] { new SqlParameter("id", id) }))
{
dtrPrize.Read();
Prize prize = new Prize();
prize.id = (int)dtrPrize[dtrPrize.GetOrdinal("id")];
prize.artitle = (string)dtrPrize[dtrPrize.GetOrdinal("artitle")];
prize.entitle = (string)dtrPrize[dtrPrize.GetOrdinal("entitle")];
prize.ardetail = (string)dtrPrize[dtrPrize.GetOrdinal("ardetail")];
prize.endetail = (string)dtrPrize[dtrPrize.GetOrdinal("endetail")];
prize.image = (string)dtrPrize[dtrPrize.GetOrdinal("image")];
prize.theme = (string)dtrPrize[dtrPrize.GetOrdinal("theme")];
prize.price = (int)dtrPrize[dtrPrize.GetOrdinal("price")];
prize.audience = (int)dtrPrize[dtrPrize.GetOrdinal("audience")];
prize.type = (byte)dtrPrize[dtrPrize.GetOrdinal("type")];
prize.status = (byte)dtrPrize[dtrPrize.GetOrdinal("status")];
prize.voucher = (string)dtrPrize[dtrPrize.GetOrdinal("voucher")];
prize.supplierid = (int)dtrPrize[dtrPrize.GetOrdinal("supplierid")];
prize.created = (DateTime)dtrPrize[dtrPrize.GetOrdinal("created")];
prize.updated = (DateTime)dtrPrize[dtrPrize.GetOrdinal("updated")];
return prize;
}