0

我有一个基本的 dll,其中包含常见的数据库方法,例如 getconnectionstring、executescalar、executenonquery、doselect 等。我正在使用(vb.net 或 c#)和 oracle。现在我需要为可能有 2-3 个 sql 的事务编写一个方法,并且只有在它们都工作时才应该提交。我想看看怎么做。我需要 sql1 返回某种唯一字段,用于插入到 sql2 和/或 sql3 中。

  private sub executeTransaction(byval sql1 as string,byval sql2 as string,byval sql3 as string)

       code to begin transaction
       execute sql1 returning unique id to a local field    'since this id may be different based on sql, how to handle this?
       execute sql2
       execute sql3 optional
       if exception rollback 
       commit on finally block and then close the connection object

  end sub

我正在寻找编写上述方法的建议/最佳实践。提前致谢。

4

1 回答 1

1

模式是:

  • 从您的连接创建交易
  • 将该事务分配给每个命令
  • 完成后提交/回滚


using(OracleConnection conn = new OracleConnection())
{
    using(DbTransaction transaction = conn.BeginTransaction())
    {
        try
        {
            // .... create a command 
            cmd1 = new OracleCommand({sql to get a value});
            cmd1.Transaction = transaction;
            cmd1.ExecuteScalar();

            // .... create another command 
            cmd1 = new OracleCommand({sql to update a value});
            cmd2.Transaction = transaction;
            cmd2.ExecuteNonQuery();

            transaction.Commit();  
        }
        catch (Exception err)
        {
            transaction.Rollback();
            throw err;   // or just throw; to preserve the deeper stack trace
        }
    }
}
于 2013-04-30T15:54:17.140 回答