使用以下方法,我可以使用ADO.NET对Oracle数据库运行事务。当我在SQL Server数据库上尝试相同的代码时,我收到错误。造成这种情况的原因是什么以及如何解决?
错误:
ExecuteNonQuery需要命令才能拥有事务 分配给该命令的连接位于挂起的本地事务中。 该命令的Transaction属性尚未初始化。
守则:
/// <summary>
/// A method to run transactional SQL on a database. Does not return a record set.
/// </summary>
/// <param name="transactions">A list of commands</param>
/// <returns>A boolean indicator of success</returns>
public bool ExecuteTransactionNonQuery(List<string> transactions)
{
if (transactions == null)
{
throw new ArgumentNullException("transactions");
}
PrepareConnection();
DbTransaction dbTransaction = DBFactoryDatabaseConnection.BeginTransaction();
try
{
foreach (var transaction in transactions)
{
DBFactoryDatabaseCommand.CommandText = transaction;
DBFactoryDatabaseCommand.CommandType = CommandType.Text;
DBFactoryDatabaseCommand.ExecuteNonQuery();
}
dbTransaction.Commit();
}
catch(Exception ex)
{
dbTransaction.Rollback();
try
{
Close();
}
catch (Exception f)
{
throw new Exception("Error: Transaction execute failed on the database. " + ex.Message + ". Following that the application failed to close the connection. " + f.Message + ". ExecuteTransactionNonQuery().");
}
throw;
}
finally
{
dbTransaction.Dispose();
}
return true;
}
答案 0 :(得分:2)
您需要将交易分配给命令。
DBFactoryDatabaseCommand.Transaction = dbTransaction;