我有一个函数,我需要添加代码来处理打开的数据库连接。 我不确定要添加的功能在哪里:
dbCommand.Dispose()
db = Nothing
不会意外破坏代码。
我可以帮助将这些代码行添加到下面的现有代码中吗?
谢谢。
代码是:
Public Shared Function SendAdminEmail() As Boolean
Dim ipAddress As String = ""
Try
ipAddress = HttpContext.Current.Request.ServerVariables("REMOTE_ADDR")
Catch ex As Exception
End Try
If (ipAddress > "") Then
Dim db As Database = DatabaseFactory.CreateDatabase(Globals.AppSettings("webdb"))
Dim dbCommand As DbCommand = db.GetStoredProcCommand("VerifySendAdminEmail")
db.AddInParameter(dbCommand, "@IPAddress", DbType.String, ipAddress)
Dim ds As DataSet = db.ExecuteDataSet(dbCommand)
If (Not ds Is Nothing) Then
If (ds.Tables.Count > 0) Then
If (ds.Tables(0).Rows.Count > 0) Then
If (ds.Tables(0).Rows(0)(0).ToString = "0") Then
Return False
End If
End If
End If
End If
End If
Return True
End Function
答案 0 :(得分:2)
如果对象使用IDisposable接口,那么您可以简单地将对象包装在using块中,该块将自动为您调用Dispose方法。对于数据库连接,它们将为您关闭连接,即使您使用早期返回调用短路功能也是如此。
Using db As Database = DatabaseFactory.CreateDatabase(Globals.AppSettings("webdb"))
Using dbCommand As DbCommand = db.GetStoredProcCommand("VerifySendAdminEmail")
db.AddInParameter(dbCommand, "@IPAddress", DbType.String, ipAddress)
Using ds As DataSet = db.ExecuteDataSet(dbCommand)
If (Not ds Is Nothing) Then
If (ds.Tables.Count > 0) Then
If (ds.Tables(0).Rows.Count > 0) Then
If (ds.Tables(0).Rows(0)(0).ToString = "0") Then
Return False
End If
End If
End If
End If
End Using
End Using
End Using