Error while disconnecting from Postgresql

Asked

Viewed 81 times

0

I am trying to make an application in C# using SGDB Postgresql, but always when I close the connection gives the following error:

Undefined object reference for an object instance.

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

 //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 (Insert) and he inserts the die but when he falls into the finally and arrives at the pgsqlConnection.Close() appears the error entered above.

1 answer

1


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

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

See this question to understand about the using: What is the usefulness 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");
    }     
}
  • I managed to understand the purpose of using, thank you!

Browser other questions tagged

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