How to ensure that all information was recorded at the bank?

Asked

Viewed 51 times

2

I’ve been realizing that I’m having trouble recording information in the bank because:

-I’m running a block of a method that records data in the database:

//codigo aqui
MySQLCallDB.InsertData("PEDIDOS", columns, values); //gravando informações
//codigo quebra por alguma Exception aqui ou seja, terei um Pedido sem Detalhes
MySQLCallDB.InsertData("PEDIDOS_DETALHES", columns, values); //gravando informações
//Restante do código

The method InsertData is a static class that manages queries in my application(MySQLCallDB) and the code and the way I call MYSQL in InsertData is:

public static string InsertData(string table, List < string > columns, List < string > values) {
    string Query = "QUERY";
    Query += "SELECT LAST_INSERT_ID() as ID;";
    MySqlCommand comm = new MySqlCommand("", conexao);
    comm.CommandText = Query;
    try {
        conexao.Open();
        MySqlDataReader reader = comm.ExecuteReader();
        reader.Read();
        return reader.GetString("ID");
    } 
    catch (Exception e) {
        Debug.WriteLine(Query);
        Debug.WriteLine(e);
        return "Error";
    } 
    finally {
      conexao.Close(); //Fechando a conexão}}
    }
}

The question is: in cases where an exception occurs that breaks the whole process (as described in the code comments), what should I do to not have information without logic within the database?

  • 1

    Use Begintransaction - Commit and catch Rollback inside the Ry. See this example: https://dev.mysql.com/doc/dev/connector-net/8.0/html/M_MySql_Data_MySqlClient_MySqlConnection_BeginTransaction.htm

  • 1

    I believe the answer to that question can help you.

  • That’s it. You have to do the Inserts and updates within a transaction according to the ACID model. https://www.diegomacedo.com.br/tag/atomicity/

1 answer

1

You will have to work with transactions, so that if nothing happens, do Commit changes and everything is stored consistently in the database, otherwise Rollback so that nothing is recorded so as not to cause inconsistencies.

// aqui pressupomos que a variável "conexao" está acessível
void GravaDadosBD()
{
    MySqlTransaction myTrans = null;

    try
    {
        conexao.Open();
        myTrans = conexao.BeginTransaction();

        MySQLCallDB.InsertData("PEDIDOS", columns, values);
        MySQLCallDB.InsertData("PEDIDOS_DETALHES", columns, values);

        // correu tudo bem, sem erros, fazer Commit()
        myTrans.Commit();
    }
    catch(Exception ex)
    {
        myTrans?.Rollback();
    }
    finally
    {
        // fechar a conexão apenas depois de executar tudo
        conexao?.Close();
    }
}

public static string InsertData(string table, List <string> columns, List <string> values) 
{
    string Query = "QUERY SELECT LAST_INSERT_ID() as ID;";
    string strResult = "Error";
    MySqlCommand comm = new MySqlCommand(Query, conexao);

    try 
    {
        MySqlDataReader reader = comm.ExecuteReader();

        reader.Read();
        strResult = reader.GetString("ID");

        reader.Close();
    }
    catch (Exception e) 
    {
        Debug.WriteLine(Query);
        Debug.WriteLine(e);
    }

    return strResult;
}
  • got it, let me ask you, if I have multiple calls that create other connections, this process will not work, it has to occur all in one connection, it proceeds?

  • No, it can be used on any connection. In the above example I put everything in the same, but could be in two separate (one for each evocation of the method InsertData).

  • John, but let’s say I wanted to use the rollback, if I apply the connection1 it will apply in connection2? Is that what I would like to know

  • No, the Rollback() only relates to the transaction associated with a connection only.

  • what the ? after transaction in mysql.transaction?.Rollback();

  • The "?" is used for the conditional null, ie it only executes the Commit() and the Rollback() case the object myTrans is not null. You can read about it here: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/null-conditional-operators

  • Thanks ! I will apply the changes in my code, if solve I mark as the correct one. But I believe that it is really the right one ;)

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.