I wonder how to use statement handles exceptions? Do I need to wrap the using statements with a Try/Cath/Finally clause in order to be sure that the SqlConnection object is closed and disposed even if the containing code throws an exception?
Public Function GetUserAccountKeyByUsername(ByVal pUsername As String) As Int32
If String.IsNullOrEmpty(pUsername) Then
Throw New ArgumentNullException("pUsername", "Username is missing")
End If
Dim o As Object
Dim userAccountKey As Int32
Dim SQL As StringBuilder = New StringBuilder()
With SQL
.Append("SELECT USER_KEY ")
.Append("FROM USER ")
.Append("WHERE USERNAME = @Username ")
End With
Try
Using conn As SqlConnection = New SqlConnection(ConnectionString)
conn.Open()
Using cmd As SqlCommand = New SqlCommand(SQL.ToString, conn)
Try
cmd.CommandTimeout = Convert.ToInt32(ConfigurationManager.AppSettings("SQLQueryLimitTime"))
cmd.Parameters.Add(New SqlParameter("@Username", SqlDbType.VarChar)).Value = pUsername
o = cmd.ExecuteScalar()
If (o IsNot Nothing) AndAlso Not (IsDBNull(o)) Then
userAccountKey = Convert.ToInt32(o)
End If
Catch ex As Exception
_log.logError(ex, cmd)
End Try
End Using
End Using
Catch ex As Exception
_log.logError(ex, conn.ConnectionString)
Finally
conn.Close()
conn.Dispose()
End Try
Return userAccountKey
End Function
You dont require to write it out again its get created automatically in complied code..
The answer is in C# but its works same way in VB.NET
using block in C# comes very handly while dealing with disposable objects. Disposable objects are those objects that can explicitly release the resources they use when called to dispose. As we know .Net garbage collection is non-deterministic so you can’t predict when exactly the object will be garbage collected.
Read this post for more in details : understanding ‘using’ block in C#
CS file code
MSIL code