I should begin by stating that I assume that the answer to this question is NO, but I wanted to ask to be sure.....If you open a sqlconnection inside of a function(with a USING block), and return from that function prior to reaching the end of the block, will that connection be disposed of properly?
For Example:
Public Function Myfunction() As Boolean
Dim ConnectionString As String = "connectionstring goes here"
Dim sql As String = "SELECT * FROM mytable"
Using connection As New SqlClient.SqlConnection(ConnectionString)
Using command As New SqlClient.SqlCommand(sql, connection)
connection.Open()
Using reader As SqlClient.SqlDataReader = command.ExecuteReader
While reader.Read
Return True
End While
End Using
End Using
End Using
Return False
End Function
Will the above connection be disposed of properly if the return true line is executed?
If you open a sqlconnection inside of a function(with a USING block), and return from that function prior to reaching the end of the block, will that connection be disposed of properly?
Yes. Absolutely. That's the beauty of a USING block. See
A Using block behaves like a Try...Finally construction in which the Try block uses the resources and the Finally block disposes of them. Because of this, the Using block guarantees disposal of the resources, no matter how you exit the block. This is true even in the case of an unhandled exception, except for a StackOverflowException
https://learn.microsoft.com/en-us/dotnet/visual-basic/language-reference/statements/using-statement
Related
I have a problem in a vb.net Windows Form project. My company is having network issues and is losing connection between the Windows Form application and the SQL server. When this happens, the application locks up and closes. Before any SQL commands are executed, is there a way to check if the SQL connection is even available?
I've tried using this:
If (cmd.Connection.State <> ConnectionState.Closed)
after the cmd is setup like this:
Dim cmd As SqlCommand
cmd = MSSQL_CONN.CreateCommand
but the state is often Open because the network connection fails after the SQL command was initialized.
I've tried to catch the error like this:
Private m_conn As SqlConnection
Try
m_conn = New SqlConnection(cn_str)
Call m_conn.Open()
Catch e As Exception
MessageBox.Show("Error")
If MSSQL_CONN.TransactionStarted Then
MSSQL_CONN.RollbackTransaction()
End If
End Try
but this has problems because it's trying to do a rollback for any other errors and the rollback throws an error because of the loss of connection state. This also starts a cascade into other timers and background processes that continue to run and try to connect to the SQL server.
I'm hoping there something like
If *SQL connection is even still available* Then
Call m_conn.Open()
Else
*Don't execute any other SQL on this form or any other background forms*
End If
Normally it's best to use a using statement for a connection where the connection is scoped to the method you are working with the database. Otherwise you could create the connection as needed e.g. check the connection state as on error.
Public Class DataOperations
Public Shared Async Function Connection() As Task(Of SqlConnection)
Dim cn As New SqlConnection With {.ConnectionString = "TODO"}
Try
Await cn.OpenAsync()
Return cn
Catch ex As Exception
Return New SqlConnection
End Try
End Function
End Class
Then there is locally scoped where the choice is OpenAsync or Open.
Public Shared Function GetCatagories() As DataTable
Dim dt As New DataTable
Using cn As New SqlConnection With {.ConnectionString = "TODO"}
Using cmd As New SqlCommand With {.Connection = cn}
cmd.CommandText = "TODO"
Try
cn.Open()
dt.Load(cmd.ExecuteReader())
Catch ex As Exception
' decide on how to handle
End Try
End Using
End Using
Return dt
End Function
EDIT:
Public Shared Async Function IsServerConnected() As Task(Of Boolean)
Using cn As New SqlConnection With {.ConnectionString = ConnectionString}
Try
Await cn.OpenAsync()
Return True
Catch ex As Exception
Return False
End Try
End Using
End Function
I'm not very experienced with vb and have inherited an application from a previous programmer. I was asked to run the Visual Studio analyse against the code to make changes as the application seemed to be causing memory issues. I got loads of messages about disposing of an object multiple times eg
Warning CA2202 Object 'myConnection' can be disposed more than once in method xxx'. To avoid generating a System.ObjectDisposedException you should not call Dispose more than one time on an object
Simple, wrap it in a using block I thought. Then I discovered myConnection was used in a try/catch
JumpUpAgain:
Try
myConnection.Open()
Catch ex As Exception
LogIt("EXCEPTION", "Connection Error: " & ex.Message)
myConnection.Close()
SqlConnection.ClearAllPools()
ConnectionString = Nothing
conn = Nothing
MySQLCmd = Nothing
myConnection = Nothing
Threading.Thread.Sleep(3000)
If ErrorLoopCounter = 5 Then
LogItDetail("Exception", "Database Connection Process failed after 5 re-tries")
If Not FailedFiles.Contains(InputFileName) Then FailedFiles.Add(InputFileName)
LogItDetail("DEBUG", "Added file to Failed Files for email")
FileProcessFailed = True
Throw
Else
ErrorLoopCounter += 1
End If
GoTo JumpUpAgain
End Try
And the myConnection object is required in later code.
I'll be taking out the myConnection=Nothing from the catch but if I put the using/end using outside of this try/catch block will it be disposed of correctly if the application hits the Throw?
The Using blocks ensure that your db objects are closed and disposed (equally as important as closing) even if there is an error. You kind of have to fit in the Try Catch since variables defined inside blocks are not visible outside the block.
Private Sub OPCode2()
Dim dt As New DataTable()
'Keep your connections local
Using cn As New MySqlConnection("Your Connection String")
Using cmd As New MySqlCommand("Select * From YourTable", cn)
Try
cn.Open()
Using dr As MySqlDataReader = cmd.ExecuteReader
dt.Load(dr) 'or whatever you want to do with your connection
End Using
Catch
'Your logging logic here
End Try
End Using
End Using
End Sub
This is the function to access the database; the connection string is perfect - There is another Function similar to this and it works fine.
Friend Shared Function AddMember(member As Object) As Task(Of Integer)
Dim connection = New SqlConnection(Configuration.ConfigurationManager.ConnectionStrings("Carrel").ConnectionString)
Dim query = New SqlCommand("INSERT INTO JSON (CATEGORY,DATA) VALUES ('MEM',#JSONString)", connection)
Try
Connection.Open()
query.Parameters.Add(New SqlParameter("#JSONString", JsonConvert.SerializeObject(member)))
Return query.ExecuteNonQueryAsync()
Catch ex As Exception
MsgBox(ex.ToString())
Throw
Finally
query.Connection.Close()
End Try
End Function
Try this:
Friend Shared Async Function AddMember(member As Object) As Task(Of Integer)
Dim cn AS New SqlConnection(Configuration.ConfigurationManager.ConnectionStrings("Carrel").ConnectionString)
Dim query As New SqlCommand("INSERT INTO JSON (CATEGORY,DATA) VALUES ('MEM',#JSONString)", cn)
Try
cn.Open()
query.Parameters.Add(New SqlParameter("#JSONString", JsonConvert.SerializeObject(member)))
Return Await query.ExecuteNonQueryAsync()
Catch ex As Exception
MsgBox(ex.ToString())
Throw
Finally
query.Connection.Close()
End Try
End Function
This should prevent the method from continuing past the ExecuteNonQueryAsync() line until the task returns, so the connection will stay open, but can still run without blocking.
It's also better practice to put the connection and command object in Using blocks, and to not worry about exceptions at this level. This is a data access method... separate that from your presentation code. Let the exception bubble up in the calling code, especially in an Async method:
Friend Shared Async Function AddMember(member As Object) As Task(Of Integer)
Using cn AS New SqlConnection(Configuration.ConfigurationManager.ConnectionStrings("Carrel").ConnectionString), _
cmd As New SqlCommand("INSERT INTO JSON (CATEGORY,DATA) VALUES ('MEM',#JSONString)", cn)
query.Parameters.Add(New SqlParameter("#JSONString", JsonConvert.SerializeObject(member)))
cn.Open()
Return Await query.ExecuteNonQueryAsync()
End Using
End Function
Just be careful, because the async code could be hiding exceptions from you now.
The problem is that, as Aman Bachas said, you're calling ExecuteNonQueryAsync which will start the operation in the background. But then your Finally block will execute and close the connection before the execute actually happens.
What you'll need to do is call the non-Async version but then do your own Async so you can close the connection after it's done.
Public Function AddMember(member As Object) As Threading.Tasks.Task(Of Integer)
Dim connection = New SqlConnection(Configuration.ConfigurationManager.ConnectionStrings("Carrel").ConnectionString)
Dim query = New SqlCommand("INSERT INTO JSON (CATEGORY,DATA) VALUES ('MEM',#JSONString)", connection)
Try
connection.Open()
query.Parameters.Add(New SqlParameter("#JSONString", JsonConvert.SerializeObject(member)))
Return Threading.Tasks.Task.Factory.StartNew(Of Integer)(Function()
Dim ret = query.ExecuteNonQuery()
connection.Close()
Return ret
End Function)
Catch ex As Exception
MsgBox(ex.ToString())
Throw
End Try
End Function
You'll probably want to add some error handling inside the task and clean this up a bit, but that should give you a starting point.
Please replace ExecuteNonQueryAsync() with the ExecuteNonQuery().
I'm using simple DataReader commands very often in my project.
To simplify it, I've created a function:
Public Function DataReaderFromCommand(ByRef uCn As SQLite.SQLiteConnection, ByVal uCommandText As String) As SQLite.SQLiteDataReader
Dim nCmdSel As SQLite.SQLiteCommand = uCn.CreateCommand
With nCmdSel
.CommandText = uCommandText
End With
Dim r As SQLite.SQLiteDataReader = nCmdSel.ExecuteReader
Return r
End Function
In my project I use it like this:
Using r As SQLite.SQLiteDataReader = DataReaderFromCommand(cnUser, "SELECT * FROM settings")
Do While r.Read
'do something
Loop
End Using'this should close the DataReader
In one case, I need to delete my database. However this fails with the error "File is locked by another process".
I tried to isolate the problem, and the locking occurs because of the function "DataReaderFromCommand".
Does anybody see what I'm doing wrong / what keeps the database locked?
I thought that after "End Using" of the datareader, the SQLiteCommand would also be disposed, so there are no further reference to the database.
You should probably be trying to do it this way:
Public Sub UsingDataReader(ByVal connectionString As String, ByVal commandText As String, ByVal action As Action(Of SQLite.SQLiteDataReader))
Using connection As New SQLite.SQLiteConnection(connectionString)
Using command As New SQLite.SQLiteCommand(commandText, connection)
Using reader = command.ExecuteReader()
action(reader)
End Using
End Using
End Using
End Sub
Then you can call the code like this:
UsingDataReader("/* your connection string here */", "SELECT * FROM settings", _
Sub (r)
Do While r.Read
'do something
Loop
End Sub)
This ensures that all of the disposable references are closed when the Sub has completed.
The first problem is that not all the disposables are being disposed of. We are assured that the connection passed to that helper is in a Using block, but the command also needs to be disposed of as it has a reference to the connection:
Dim cmd As New SQLiteCommand(sql, dbcon)
Even if you dont use the overloaded constructor, in order to work, somewhere you set the connection property. This illustrates one of the problems with such "DB helper" methods: the DBConnection, DBCommand and DBReader objects work together very closely, but they are created in different methods with different scopes and you can't normally see if everything is being cleaned up properly.
The code posted will always fail because that DBCommand object - and by extension the DBConnection - are not disposed. But even if you clean up properly, pooling will keep the DBConnection alive for a while as jmcilhinney explains. Here are 2 fixes:
Clear the Pool
Using dbcon As New SQLiteConnection(LiteConnStr),
cmd As New SQLiteCommand(sql, dbcon)
dbcon.Open()
Dim n As Int32 = 0
Using rdr = cmd.ExecuteReader
While rdr.Read
' == DoSomething()
Console.WriteLine("{0} == {1}", n, rdr.GetString(0))
n += 1
End While
End Using
' Clears the connection pool associated with the connection.
' Any other active connections using the same database file will be
' discarded instead of returned to the pool when they are closed.
SQLiteConnection.ClearPool(dbcon)
End Using
File.Delete(sqlFile)
The dbCon and cmd objects are "stacked" into one Using statement to reduce indentation.
This will close and discard any and all connections in the pool, provided they have been Disposed - as well as any objects which reference them. If you use Dim cmd ... you will need to explicitly dispose of it.
Force Garbage Collection
I think this is much more ham-fisted, but it is included for completeness.
Using dbcon As New SQLiteConnection(LiteConnStr),
cmd As New SQLiteCommand(sql, dbcon)
...
Using rdr = cmd.ExecuteReader
...
End Using
End Using
GC.WaitForPendingFinalizers()
File.Delete(sqlFile)
This also works as long as everything has been properly disposed of. I prefer not to mess with GC unless absolutely necessary. The issue here is that clean up will not be limited to DBProvider objects but anything which has been disposed and is awaiting GC.
Yet a third workaround would be to turn off pooling, but you would still have to dispose of everything.
You are going to need to also close your cnUser connection to the database.
Closing/disposing the reader does not necessarily close/dispose the open connection.
Will the following statement cause a memory leak:
Imports System.Data.SQLClient
Public Function getConnection () As SQLConnection
return New SQLConnection()
End Function
Public Sub TestConnection()
Dim con As SQLConnection
con = getConnection
con.close
con = Nothing
End Sub
How does .close or .dispose get called on the SQLConnection in getConnection?
You're returning a reference type, hence you operate on the same instance in TestConnection so no memory leak here.
At the end you have 2 instances with null (gc will collect them), but the connection is closed.
There will be no memory leak because it will be garbage collected after you've called the method.
But this method does nothing but causing confusion. You should always dispose connections(which closes it implicitely) as soon as you're finished with it (even in case of an exception).
You can do that in a finally of a Try/Finally or (easier) with the Using statement. But since both approaches need to wrap the connection, your method enables the calling method to forget it. Therefore it is bad practise.
So simply do this:
Public Sub TestConnection()
Using con = New SqlConnection("connection string here")
Using cmd = new SqlCommand("sql query here", con)
' do something, f.e. cmd.ExecuteNonQuery() '
End Using
End Using
End Sub