【发布时间】:2012-01-31 09:23:28
【问题描述】:
我想知道如何使用语句处理异常? 我是否需要用 Try/Cath/Finally 子句包装 using 语句,以确保 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
【问题讨论】:
-
你还有什么问题吗?
-
如果你得到你想要的信息,不要忘记将答案标记为已接受...
标签: .net vb.net ado.net using-statement