Search code examples
npgsql

Will NpgsqlConnection.Open throw an error if the port is closed?


I wrote a test and at the time it seemed that if I had

NpgsqlConnection connection = new NpgsqlConnection(<valid string with port #>);
connection.Open();
...

with the corresponding network port closed, then connection.Open() would throw an exception. Now the code is

using (NpgsqlConnection connection = new NpgsqlConnection(builder.ConnectionString))
{
    connection.Open();
    ...

and I am getting feedback that this code may actually continue even if the port is closed. What is the behavior of NpgsqlConnection - is it guaranteed that connection.Open() will throw if the specified port is not opened?

I tried examining NpgsqlConnection.cs and NpgsqlConnector.cs but couldn't pin it down. Any help would be appreciated


Solution

  • Yes, NpgsqlConnection.Open() will throw an exception if PostgreSQL isn't running on the potty specified ("connection refused").

    Adding a using does nothing more than dispose the connection at the end of the block, after the exception has already been thrown.