我想知道如何使用语句处理异常? 我是否需要将使用语句包装在 Try/Catch/Finally 语句中,以确保即使包含代码引发异常,SqlConnection 对象也会被关闭和处理?
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