I am running a simple select query thusly:
Private Function ReturnTableQuery(ByVal SQL As String) As DataTable
Dim rs As DataTable = New DataTable
Dim Adapter As NpgsqlDataAdapter = New NpgsqlDataAdapter
Try
If conn Is Nothing Then
ConnectDatabase()
End If
If conn.State <> ConnectionState.Open Then
ConnectDatabase()
End If
Adapter.SelectCommand = New NpgsqlCommand(SQL, conn)
Adapter.SelectCommand.CommandTimeout = 10
Adapter.Fill(rs)
Catch ex As Exception
PreserveStackTrace(ex)
Throw ex
End Try
Return rs
End Function
The SQL command is:
Select id, application, datetimestamp, status, data, attemptcount from queue where application='reportengine' and status=4 and datetimestamp <= now() order by datetimestamp limit 1
I sometimes get 0 rows returned.
If I run the exact same query in pgAdmin while it is failing in my program, it returns a row as expected.
If I close and re-open the connection it works, but I can’t determine if there is anything wrong with the connection beforehand.
I could just re-open the connection every time, but I would rather not recreate the connection as often as I would need to.
I am also getting intermittent errors like “unknown server response” which I am catching and re-opening the connection.
Any ideas why the connection is so fragile and is there an inexpensive way to check the actual connection status?
Thx,
Brad
Are you sharing your connection between multiple threads? Npgsql, as other data providers, is not thread safe. I would rank this is the most probable cause of your problems. You should open a connection, use it and then close it. That’s the most scalable pattern when using a connection pool. I hope it helps.