Error when disconnecting from PostgreSQL

0

I'm trying to make a C # application with PostgreSQL SGDB, but whenever I close the connection it gives the following error:

  

Object reference not set to an instance of an object.

I'm using mono.security and npgsql2 but I could not add the current one.

 //Inserir registros

public void ExecutarSQL(string sql)
{
    try
    {
        using (NpgsqlConnection pgsqlConnection = new NpgsqlConnection(connString))
        {
            //Abra a conexão com o PgSQL                  
            pgsqlConnection.Open();
            string cmdInserir = sql;

            using (NpgsqlCommand pgsqlcommand = new NpgsqlCommand(cmdInserir, pgsqlConnection))
            {
                int i = pgsqlcommand.ExecuteNonQuery();
            }
        }
    }
    catch (NpgsqlException ex)
    {
        MessageBox.Show("npgsql");
    }
    catch (Exception ex)
    {
        MessageBox.Show("exp");
    }
    finally
    {
        MessageBox.Show("fecha");
        pgsqlConnection.Close();
    }     
}

In the case in question I can pass an SQL to the function and it inserts the data however when it falls into finally and arrives at pgsqlConnection.Close() the above error appears.

    
asked by anonymous 12.12.2016 / 16:03

1 answer

1

It happens that at time of finally the variable pgsqlConnection is null because using is in charge of making Dispose of the variable for you.

Directly speaking, this operation is not required in block finally , since using already does this.

See this question to understand about using : What is the use of using?

The code should be:

public void ExecutarSQL(string sql)
{
    try
    {
        using (NpgsqlConnection pgsqlConnection = new NpgsqlConnection(connString))
        {
            //Abra a conexão com o PgSQL                  
            pgsqlConnection.Open();
            string cmdInserir = sql;

            using (NpgsqlCommand pgsqlcommand = new NpgsqlCommand(cmdInserir, pgsqlConnection))
            {
                int i = pgsqlcommand.ExecuteNonQuery();
            }
        }
    }
    catch (NpgsqlException ex)
    {
        MessageBox.Show("npgsql");
    }
    catch (Exception ex)
    {
        MessageBox.Show("exp");
    }
    finally
    {
        MessageBox.Show("fecha");
    }     
}
    
12.12.2016 / 16:09