views:

145

answers:

2

I want to do an insert and an update on 2 separate tables, but have them be in 1 transaction).

Essentially in pseudocode I want to do something like:

MySqlTransaction trans = null;
try
{
    _Connection.Open();
    trans = _Connection.BeginTransaction();
    insertCmd.Transaction = trans;
    updateCmd.Transaction = trans;

    Int32 id = insertCmd.ExecuteNonQuery();
    updateCmd.Parameters.Add(new MySqlParameter("oid", MySqlDbType.Int32).Value = id);
    updateCmd.ExecuteNonQuery();
}
catch(MySqlException)
{
    if(trans != null)
        trans.RollBack();
}
finally
{
    _Connection.Close();
}

is this possible or am I going about this the wrong way?

+3  A: 

Yes, you can execute multiple commands within a single transaction. This would let you do exactly what you are trying to do: all commands, or none of them.

Elie
+4  A: 

Yes you can if:

  • All the tables support it, (InnoDB tables support it, but MyIsam tables don't)
  • The queries don't affect the database-schema. (ALTER TABLE, DROP TABLE, CREATE TABLE, etc causes the transaction to commit)
Bob Fanger