Open connection more than once in C #

0

I'm developing a service in C #.

  • calls a function to check if it has active records.
  • If I have a record I call another function to select the data for the first query.
  • When I run my service, the connection error already occurs.

    So before calling each function I make a reader.Close(); and I do not open the connection in the other functions anymore. But I do not know if this is correct and if it would be the right way.

    Step1

    public int VerifyStatus30(List<Class.ReturnTableName> tableInfo)
        {
            try
            {
                var countDis = 0;
    
                using (MySqlConnection conn = DB.DatabaseConnection.getHSDBConnection())
                {
                    conn.Open();
                    MySqlCommand command = new MySqlCommand("SELECT DataObj, RecId FROM HS_REGISTRIES WHERE ErrorCode = 0 AND HandleStatus = 30 ORDER BY UpdateDate30 ASC LIMIT 1", conn);
    
                    using (MySqlDataReader reader = command.ExecuteReader())
                    {
                        if (reader.HasRows)
                        {
                            countDis = 1;
                            while (reader.Read())
                            {
                                int dataObj = reader.GetInt32(0);
                                int recId = reader.GetInt32(1);
                                reader.Close();
    
                                ClassTable.ReturnSapId returnSapId = new ClassTable.ReturnSapId();
                                returnSapId.GetSapId(recId, dataObj, tableInfo);
                            }
                        }
                    }
                }
    
                return countDis; // retorna a variável quantidade
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
    

    Step2

    public void GetSapId(int recId, int dataObj, List<Class.ReturnTableName> tableInfo)
        {
            try
            {
                Class.ReturnTableName result = tableInfo.Find(x => x.IdIntegraHardness == dataObj);
    
                using (MySqlConnection conn = DB.DatabaseConnection.getHSDBConnection())
                {
                    //conn.Open();
                    MySqlCommand command = new MySqlCommand("SELECT AbsEntry,u_D005_id FROM HS501_ONCM WHERE RecId = @recId", conn);
                    command.Parameters.AddWithValue("@tableName", result.TableIntegraHardness.Replace("'", ""));
                    command.Parameters.AddWithValue("@recId", recId);
    
                    using (MySqlDataReader reader = command.ExecuteReader())
                    {
                        if (reader.HasRows)
                        {
                            while (reader.Read())
                            {
                                int idSAP = reader.GetInt32(0);//ID SAP
                                int idHardness = reader.GetInt32(1);//ID HARDNESS
    
                                Class.UpdateStatus updateStatus = new Class.UpdateStatus();
                                reader.Close();
                                updateStatus.Update40(recId, 1);
                                SaveIdSH(idSAP,idHardness, tableInfo, dataObj);
                                updateStatus.Update50(recId, 1);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
    
        
    asked by anonymous 24.10.2018 / 18:53

    2 answers

    1

    Why catch an exception to throw it again? What advantage do you think you have in this? Only disadvantage! Why close something that will be closed more robustly and correctly at the end of using ? And contrary to what was said in the other answer you do not have to use finally . If the connection is open pass it to the other method instead of opening it again. I'm going to write a better code, but in fact all this architecture is already bad, but it's not the focus of the question to solve this, nor is it worth much because almost everyone does it wrong. Here's how the code gets cleaner:

    public int VerifyStatus30(List<Class.ReturnTableName> tableInfo) {
        var countDis = 0;
        using (var conn = MySqlConnection(Ambiente.ConnectionString)) { //isto estaria em uma classe estática que tem a string, mas pode por na mão
        conn.Open();
        var command = new MySqlCommand("SELECT DataObj, RecId FROM HS_REGISTRIES WHERE ErrorCode = 0 AND HandleStatus = 30 ORDER BY UpdateDate30 ASC LIMIT 1", conn);
        using (var reader = command.ExecuteReader()) {
            if (reader.HasRows) {
                countDis = 1;
                while (reader.Read()) {
                    int dataObj = reader.GetInt32(0);
                    int recId = reader.GetInt32(1);
                    ClassTable.ReturnSapId returnSapId = new ClassTable.ReturnSapId();
                    returnSapId.GetSapId(recId, dataObj, tableInfo, conn);
                }
            }
        }
        return countDis;
    }
    
    public void GetSapId(int recId, int dataObj, List<Class.ReturnTableName> tableInfo, MySqlConnection conn) {
        Class.ReturnTableName result = tableInfo.Find(x => x.IdIntegraHardness == dataObj);
        var command = new MySqlCommand("SELECT AbsEntry,u_D005_id FROM HS501_ONCM WHERE RecId = @recId", conn);
        command.Parameters.AddWithValue("@tableName", result.TableIntegraHardness.Replace("'", ""));
        command.Parameters.AddWithValue("@recId", recId);
        using (var  reader = command.ExecuteReader()) {
            if (reader.HasRows) {
                while (reader.Read()) {
                    int idSAP = reader.GetInt32(0);//ID SAP
                    int idHardness = reader.GetInt32(1);//ID HARDNESS
                    Class.UpdateStatus updateStatus = new Class.UpdateStatus();
                    updateStatus.Update40(recId, 1);
                    SaveIdSH(idSAP,idHardness, tableInfo, dataObj);
                    updateStatus.Update50(recId, 1);
                }
            }
        }
    }
    

    I placed GitHub for future reference .

        
    24.10.2018 / 19:49
    0

    At the end of each function, you can end the connection to the independent database if it fails or not, use the finally block {}:

    public int VerifyStatus30(List<Class.ReturnTableName> tableInfo)
        {
            try
            {
                var countDis = 0;
    
                using (MySqlConnection conn = DB.DatabaseConnection.getHSDBConnection())
                {
                    conn.Open();
                    MySqlCommand command = new MySqlCommand("SELECT DataObj, RecId FROM HS_REGISTRIES WHERE ErrorCode = 0 AND HandleStatus = 30 ORDER BY UpdateDate30 ASC LIMIT 1", conn);
    
                    using (MySqlDataReader reader = command.ExecuteReader())
                    {
                        if (reader.HasRows)
                        {
                            countDis = 1;
                            while (reader.Read())
                            {
                                int dataObj = reader.GetInt32(0);
                                int recId = reader.GetInt32(1);
                                reader.Close();
    
                                ClassTable.ReturnSapId returnSapId = new ClassTable.ReturnSapId();
                                returnSapId.GetSapId(recId, dataObj, tableInfo);
                            }
                        }
                    }
                }
    
                return countDis; // retorna a variável quantidade
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
           finally
           {
              conn.Close();
           }
        }
    
        
    24.10.2018 / 18:58