gpt4 book ai didi

c# - 使用 SqlCommand 和范围

转载 作者:行者123 更新时间:2023-11-30 16:15:34 25 4
gpt4 key购买 nike

谁能告诉我是否有充分的理由使用以下两个代码块之一而不是另一个?

using (SqlTransaction mySqlTransaction = mySqlConnection.BeginTransaction)
{
using (SqlCommand mySqlCmd =
new SqlCommand("First of many SQL statements here", mySqlConnection, mySqlTransaction)
{
mySqlCmd.Parameters.Add("@MyFirstParm", SqlDbType.Int).Value = myFirstVal;
mySqlCmd.ExecuteNonQuery();
}

using (SqlCommand mySqlCmd =
new SqlCommand("Second of many SQL statements here", mySqlConnection, mySqlTransaction)
{
mySqlCmd.Parameters.Add("@MySecondParm", SqlDbType.Int).Value = mySecondVal;
mySqlCmd.ExecuteNonQuery();
}

.
.
.

sqlTransaction.Commit();
}

对比

using (SqlTransaction mySqlTransaction = mySqlConnection.BeginTransaction)
{
using (SqlCommand mySqlCmd = new SqlCommand("", mySqlConnection, mySqlTransaction)
{
mySqlCmd.Parameters.Add("@MyFirstParm", SqlDbType.Int).Value = myFirstVal;
mySqlCmd.Parameters.Add("@MySecondParm", SqlDbType.Int).Value = mySecondVal;

mySqlCmd.CommandText = "First of many SQL statements here";
mySqlCmd.ExecuteNonQuery();

mySqlCmd.CommandText = "Second of many SQL statements here";
mySqlCmd.ExecuteNonQuery();

.
.
.
}

sqlTransaction.Commit();
}

最佳答案

我会选择 1,因为每个 SqlCommand 都有一组新的参数。

我还建议将它们移动到单独的方法中,甚至将其作为一个存储过程。

关于c# - 使用 SqlCommand 和范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19427694/

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