Search code examples
c#mysqltransactionscommitrollback

What happens if there is a power outage before calling commit or rollback?


So I've been testing with this code:

MySqlTransaction trans = null;
                    var con = new MySqlConnection(DBInfo.CON_STRING);
                    try
                    {

                            con.Open();
                            trans = con.BeginTransaction();

                            var query = "INSERT INTO test (num) VALUE (@val1)";
                            var cmd = new MySqlCommand(query, con);
                            cmd.Transaction = trans;
                            cmd.Prepare();

                            cmd.Parameters.AddWithValue("@val1", 0);

                            for (int i = 0; i <= 15; i++)
                            {

                                    cmd.Parameters["@val1"].Value = i;
                                    cmd.ExecuteNonQuery();
                                    if (i == 10)
                                    {
                                            //throw new DivideByZeroException();
                                            MessageBox.Show("pause");
                                    }
                            }

                            trans.Commit();
                    }
                    catch (Exception ex)
                    {

                            MessageBox.Show(ex.StackTrace);

                            try
                            {
                                if (trans != null) trans.Rollback();
                            }
                            catch (Exception ex1)
                            {
                                    MessageBox.Show(ex1.Message);
                            }
                    }
                    finally
                    {
                        con.Close();
                    }

The commit and rollback method. And i have a question. In the for block i have a MessageBox to pause the execution of the code so i can stop the program to simulate a sudden execution of the program. Thing is that the query didn't commit but what happened to the server then? Does it rollback automatically? and what happens if for example the PC where the program is running happens to be the server and there is a power outage? (let say the power outage happened in the middle of the execution of the for block.


Solution

  • When a database server restarts after a power outages, it reverts back to a clean state that contains only committed work.

    When a database client gets cut off in the middle of a transaction, the server will clean up the transaction automatically by rolling it back.