Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you have multiple MySqlCommand's in a single transaction?

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?

like image 547
Steven Evers Avatar asked Mar 16 '09 18:03

Steven Evers


People also ask

Does MySQL support transactions?

MySQL supports local transactions (within a given client session) through statements such as SET autocommit , START TRANSACTION , COMMIT , and ROLLBACK . See Section 13.3. 1, “START TRANSACTION, COMMIT, and ROLLBACK Statements”. XA transaction support enables MySQL to participate in distributed transactions as well.

How to set transaction in MySQL?

To set the transaction access mode, use a READ WRITE or READ ONLY clause. It is not permitted to specify multiple access-mode clauses in the same SET TRANSACTION statement. By default, a transaction takes place in read/write mode, with both reads and writes permitted to tables used in the transaction.

What is implicit COMMIT in MySQL?

3 Statements That Cause an Implicit Commit. The statements listed in this section (and any synonyms for them) implicitly end any transaction active in the current session, as if you had done a COMMIT before executing the statement. Most of these statements also cause an implicit commit after executing.

Does MySQL auto commit?

By default, MySQL runs with autocommit mode enabled. This means that, when not otherwise inside a transaction, each statement is atomic, as if it were surrounded by START TRANSACTION and COMMIT .


1 Answers

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)
like image 99
Bob Fanger Avatar answered Sep 21 '22 00:09

Bob Fanger