我正在尝试编写一种方法,用户可以在其中以字符串数组格式传递多个 sql 语句。并创建交易。必要时回滚。目前我收到一条错误消息,指出事务需要执行命令。任何建议将不胜感激,也许是另一种(或正确)的方式来做我需要做的事情。以下是现有代码。
public bool Scalar(params string[] sqlTexts)
{
SqlTransaction tran = null;
try
{
using (SqlConnection connection = new SqlConnection(strConnectionString)) // Auto dispose of connection
{
connection.Open(); // Open the connection
using (tran = connection.BeginTransaction())
{
using (SqlCommand cmdCommand = connection.CreateCommand()) // Auto dispose of command
{
foreach (string currentSQL in sqlTexts)
{
cmdCommand.CommandText = currentSQL;
cmdCommand.ExecuteScalar();
}
}
tran.Commit();
}
}
return true;
}
catch (Exception)
{
if (tran != null)
tran.Rollback();
return false;
}
}