gpt4 book ai didi

c# - 带有 using 关键字的 SqlDataAdapter

转载 作者:太空狗 更新时间:2023-10-30 00:53:44 25 4
gpt4 key购买 nike

下面的代码是否健康?或者我不需要使用 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 返回给某个方法,它将关闭连接。那么您认为以下技术适用于 DataReaderusing 关键字吗:

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;
}

最佳答案

健康的;我个人认为不健康的部分是它使用 DataSetDataAdapter 的部分,但这也许只是我个人的偏见。

是的,你应该在这里处理适配器等(这显然是 using 为你所做的)。

作为一个微不足道的无意义的整理,你可以堆叠 using - 只是让它不那么冗长:

using (SqlConnection con = new SqlConnection(ConStr))
using (SqlCommand cmd = con.CreateCommand())
{

关于c# - 带有 using 关键字的 SqlDataAdapter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15333522/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com