我在一个更大的项目中拥有一个实用程序功能,该功能可以更新后端SQL数据库。我大多数时候都无法使用它,并显示以下错误:
已经有一个与此命令关联的打开的DataReader,必须先关闭它。
该功能的代码如下:
Public Function Update_Data(what As String, Optional where As String = "",
Optional table As String = ThisAddIn.defaultTable) As Integer
Try
Dim cmd As New SqlCommand With {
.Connection = conn
}
cmd.CommandText = "UPDATE " & table & " SET " & what
If where <> "" Then
cmd.CommandText &= " WHERE " & where
End If
Update_Data = cmd.ExecuteNonQuery
cmd.Dispose()
Catch ex As Exception
Update_Data = 0
Debug.WriteLine("SQL Error updating data:" & vbCrLf & ex.Message)
End Try
End Function
我已经遍历了代码的其余部分,以确保每当我声明一个SQLDataReader
时,我以后都会调用reader.close()
。我在其中添加了cmd.Dispose()
行以及我可以找到的所有其他ExecuteNonQuery
函数-万一有帮助?
还有其他可能未关闭的阅读器实例/类型吗?
答案 0 :(得分:0)
在发生异常的情况下,您不会处置命令。
如果您不想使用Using
,请添加一个Finally
Public Function Update_Data(what As String, Optional where As String = "",
Optional table As String = ThisAddIn.defaultTable) As Integer
Dim cmd As SqlCommand
Try
cmd = New SqlCommand With {.Connection = conn}
cmd.CommandText = "UPDATE " & table & " SET " & what
If where <> "" Then
cmd.CommandText &= " WHERE " & where
End If
Update_Data = cmd.ExecuteNonQuery
Catch ex As Exception
Update_Data = 0
Debug.WriteLine("SQL Error updating data:" & vbCrLf & ex.Message)
Finally
cmd.Dispose()
End Try
End Function
但是Using
可能更简单
Public Function Update_Data(what As String, Optional where As String = "",
Optional table As String = ThisAddIn.defaultTable) As Integer
Using cmd As New SqlCommand With {.Connection = conn}
Try
cmd.CommandText = "UPDATE " & table & " SET " & what
If where <> "" Then
cmd.CommandText &= " WHERE " & where
End If
Update_Data = cmd.ExecuteNonQuery
Catch ex As Exception
Update_Data = 0
Debug.WriteLine("SQL Error updating data:" & vbCrLf & ex.Message)
End Try
End Using
End Function