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

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

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.

Related

Try Catch not catching Database connection error

I'm using the following code to open a database connection. If the connection fails for any reason, I get the typical VB error message with all of the details. and my program stops. It does not give me my graceful message and ending.
My try/catch does not work regardless of the connection error (whether it is password related, network related, or sql server related).
I need my program to continue on even if I can't connect to the database.
Public Class SQL_Connection
Public conn As New SqlConnection
Public cmd As New SqlCommand
Public Sub New()
conn.ConnectionString = my_connection_string
Try
conn.Open()
Catch ex As Exception
MessageBox.Show("Unable to open database. " + ex.ToString)
End Try
cmd = conn.CreateCommand()
End If
End Sub
End Class
Have a look at this article.
If the program is not run in debug mode, the try catch would do it's thing right away with out stopping the execution.

How to get rid of "The connection was not closed. The connection's current state is open." error? [duplicate]

I'm writing an ASP.NET application. In my datalayer an sql connection is being opened and closed before and after querying. The SqlConnection is being kept as a private field of a single class. Every database call in the class uses the same structure:
conn.Open();
try
{
// database querying here
}
finally
{
conn.Close();
}
Yet, on very rare occasions I get the exception 'The connection was not closed. The connection's current state is open'. It's not possible to reproduce the problem since it originates very rarely from different parts of the code. There is some threading involved in my application but new threads also make new data layer classes and thus new connection objects.
I do not understand how it's possible to have a connection lingering around open using the code above. Shouldn't the connection always be closed after opening, making it impossible for the above exception to occur?
It's likely that an exception is being thrown in the try block that you aren't handling. See this note in MSDN for try-finally:
Within a handled exception, the associated finally block is guaranteed to be run. However, if the exception is unhandled, execution of the finally block is dependent on how the exception unwind operation is triggered.
I would recommend wrapping the connection in a using block anyway:
using (SqlConnection connection = new SqlConnection(connectionString))
{
//etc...
}
Alternatively, add a catch block to the try-finally:
conn.Open();
try
{
}
catch
{
}
finally
{
conn.Close();
}
you should close connections as soon as you operations finished. Try to open connections for the shortest time possible.
However it is best to use using it will call Dispose method even in case of exceptions.
using (SqlConnection conn= new SqlConnection(conStr))
{
//etc...
}
OR
1) Open the connection
2) Access the database
3) Close the connection
//conn.Open();
try
{
conn.Open();
//Your Code
}
finally
{
conn.Close();
conn.Dispose();//Do not call this if you want to reuse the connection
}

Is SQL Server available

I'm using VB.NET to create a simple application which will test if a variety of SQL Server are available online.
I have the code below, but the timeout is not working and it simply waits forever rather than throwing a timeout error. I have put breakpoints in and, as this is in an loop of IP's, it never progresses if the IP being checked is unavailable.
Dim data As New SqlClient.SqlConnection("Data Source=DatabaseIP;Initial Catalog=POS;Integrated Security=False;User ID=sa;Password=;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False".Replace("DatabaseIP", IP))
Try
data.Open()
Catch ex As Exception
Dim stophere As String = ""
TextBox1.Text += IP + vbNewLine
End Try
Connect Timeout=15 is not correct, try it with Connection Timeout=15
To connect with Database, following code is enough,
Dim data As New SqlClient.SqlConnection("Data Source=DatabaseIP;Initial Catalog=POS;Integrated Security=False;User ID=sa;Password=;")

Does the SQL connection not get closed if you put the datareader in a using block?

So, I recently inherited a large project that uses the following data access pattern; unfortunately, this is resulting in a massive number of timeout exceptions related to connection pooling.
Timeout expired. The timeout period elapsed prior to obtaining a
connection from the pool. This may have occurred because all pooled
connections were in use and max pool size was reached"
It clear that the connections are leaking and not getting closed properly.
So, the framework has a DataAccess class with the method GetDataReader.
When the data reader is referenced, it is placed inside a using block, but connections are still leaking.
Does the fact that the connection is not explicitly closed or placed in a using block the reason why the connections are getting leaked?
Normally, I would wrap the connection in a using block AND wrap the data reader in a using block.
Obviously, this framework is very flawed, but would somehow using the option CommandBehavior.CloseConnection for the data reader resolve this issue?
None the external code accesses the SqlConnection directly and has to go through this DataAccess class.
public IDataReader GetDataReader(QueryDto dto)
{
DateTime current = DateTime.Now;
Database db = DatabaseFactory.CreateDatabase(dto.DatabaseName);
DbCommand cmd = db.GetStoredProcCommand(dto.StoredProcedureName);
if (dto.Params.Length > 0)
{
cmd = db.GetStoredProcCommand(dto.StoredProcedureName, dto.Params);
}
dto.Command = cmd;
cmd.CommandTimeout = dto.Timeout;
cmd.Connection = db.CreateConnection();
try
{
cmd.Connection.Open();
}
catch (SqlException ex)
{
// Handle Exception here...
throw;
}
return rdr;
}
Usage in some static repository class:
var query = new QueryDto
{
DatabaseName = "SomeDatabase",
Params = parms,
StoredProcedureName = "StoredProcedureName"
};
using (IDataReader dr = dataAccess.GetDataReader(query))
{
while (dr.Read())
{
// do stuff here
}
}
I think your problem is that the using statement is around a function that has open resources embedded in it. The using will not dispose of the connection that is opened inside GetDataReader. I think your are correct that the Connection itself needs to be in a using block. The using statement only calls Dispose on the object that is passed in, not any nested resources.

Why is my using statement not closing connection? [duplicate]

This question already has an answer here:
Closed 11 years ago.
Possible Duplicate:
Entity framework 4 not closing connection in sql server 2005 profiler
Well, lots of developers on stackoverflow are saying that I should not worry to close my connection: my using statement will close the connection for me, here and here and all over the site. Unfortunately, I do not see it happening. Here is my code:
[Test, Explicit]
public void ReconnectTest()
{
const string connString = "Initial Catalog=MyDb;Data Source=MyServer;Integrated Security=SSPI;Application Name=ReconnectTest;";
for (int i = 0; i < 2000; i++)
{
try
{
using (var conn = new SqlConnection(connString))
{
conn.Open();
using (var command = conn.CreateCommand())
{
command.CommandText = "SELECT 1 as a";
command.CommandType = CommandType.Text;
command.ExecuteNonQuery();
}
//conn.Close();
// optional breakpoint 1 below
}
}
catch(SqlException e)
{
// breakpoint 2 below
Console.WriteLine(e);
}
// breakpoint 3 below
}
}
When I enable all breakpoints and start my test, the first iteration succeeds, and I hit breakpoint 3. At this point, the connection is still open: I see it in the Profiler, and sp_who2 outputs it too.
Let's suppose that at this time I am out for a lunch, and my connection is idle. As such, our production server kills it. To imitate it, I am killing the connection from SSMS.
So, when I hit F5 and run the second iteration, my connection is killed. Unfortunately, it does not reopen automatically, so ExecuteNonQuery throws the following exception: "transport-level error has occurred". When I run the third iteration, my connection actually opens: I see it as an event in Profiler, and sp_who2 outputs it as well.
Even when I have uncommented my conn.Close() command, the connection still does not close, and when I kill it from SSMS, the next iteration still blows up.
What am I missing? Why can't using statement close my connection? Why can't Open() actually open it the first time, but succeeds the next time?
This question has originated from my previous one
When you call SqlConnection.Dispose(), which you do because of the using block, the connection is not closed, per-se. It is released back to the connection pool.
In order to avoid constantly building/tearing down connections, the connection pool will keep connections open for your application to use. So it makes perfect sense that the connection would still show as being open.
What's happening after that, I can't explain offhand - I know that keeping a random connection open would not cause that, though, because your application can certainly make more than a single concurrent connection.

Resources