我应该在Try / Catch块中包装ADODB.RecordSet.Open/Close方法吗?

时间:2017-10-12 11:47:05

标签: vb.net exception-handling recordset

我正在将旧的VB6应用程序重新编写到VB.NET中,我想提高代码质量。 我无法为ADODB.RecordSet找到好的API文档,Open()和Close()方法是否会抛出异常。

使用时,我应该在Try / Catch块中包装这两个方法吗?他们会抛出一些例外吗?

但从逻辑上讲,它们应该抛出异常,因为它们都在访问作为外部资源的数据库。

1 个答案:

答案 0 :(得分:0)

是的,我确实包装了我的代码,它运行得很好。我做了这样的实用功能:

Public Sub CloseRecordSet(ByRef recordSet As ADODB.Recordset)
    Try
        If recordSet.State = ADODB.ObjectStateEnum.adStateOpen Then
            recordSet.Close()
        End If
    Catch ex As Exception
        Dim funcName As String = System.Reflection.MethodInfo.GetCurrentMethod().Name
        SV_DZS_Utils.PrintToConsole(funcName & ": " & ex.Message & ", Source: " & ex.Source & ", StackTrace: " & ex.StackTrace)
    Finally
        recordSet = Nothing
    End Try
End Sub

Public Sub OpenRecordSetForwardReadOnly(ByRef recordSet As ADODB.Recordset, ByVal sql As String, ByRef dbConn As ADODB.Connection)
    Try
        recordSet.Open(sql, dbConn, ADODB.CursorTypeEnum.adOpenForwardOnly, ADODB.LockTypeEnum.adLockReadOnly, ADODB.CommandTypeEnum.adCmdText)
    Catch ex As Exception
        Dim funcName As String = System.Reflection.MethodInfo.GetCurrentMethod().Name
        SV_DZS_Utils.PrintToConsole(funcName & ": " & ex.Message & ", Source: " & ex.Source & ", StackTrace: " & ex.StackTrace)
    End Try
End Sub

Public Sub OpenRecordSetDynamic(ByRef recordSet As ADODB.Recordset, ByVal sql As String, ByRef dbConn As ADODB.Connection)
    Try
        recordSet.Open(sql, dbConn, ADODB.CursorTypeEnum.adOpenDynamic, , ADODB.CommandTypeEnum.adCmdText)
    Catch ex As Exception
        Dim funcName As String = System.Reflection.MethodInfo.GetCurrentMethod().Name
        SV_DZS_Utils.PrintToConsole(funcName & ": " & ex.Message & ", Source: " & ex.Source & ", StackTrace: " & ex.StackTrace)
    End Try
End Sub