无法在VB.NET中将OledbDataReader关闭到Sybase数据库
时间:2020-03-06 14:39:23 来源:igfitidea点击:
从其中读取数据后,我似乎无法关闭OledbDataReader对象。这是相关的代码-
Dim conSyBase As New OleDb.OleDbConnection("Provider=Sybase.ASEOLEDBProvider.2;Server Name=xx.xx.xx.xx;Server Port Address=5000;Initial Catalog=xxxxxxxxxx;User ID=xxxxxxxx;Password=xxxxxxxxx;") conSyBase.Open() Dim cmdSyBase As New OleDb.OleDbCommand("MySQLStatement", conSyBase) Dim drSyBase As OleDb.OleDbDataReader = cmdSyBase.ExecuteReader Try While drSyBase.Read /*Do some stuff with the data here */ End While Catch ex As Exception NotifyError(ex, "Read failed.") End Try drSyBase.Close() /* CODE HANGS HERE */ conSyBase.Close() drSyBase.Dispose() cmdSyBase.Dispose() conSyBase.Dispose()
控制台应用程序只是挂在我试图关闭阅读器的位置。打开和关闭连接不是问题,因此有人对导致此问题的原因有任何想法吗?
解决方案
这是一个长镜头,但是请尝试在Try的Final代码块中移动.Close()和.Dispose()行。像这样:
Dim conSyBase As New OleDb.OleDbConnection("Provider=Sybase.ASEOLEDBProvider.2;Server Name=xx.xx.xx.xx;Server Port Address=5000;Initial Catalog=xxxxxxxxxx;User ID=xxxxxxxx;Password=xxxxxxxxx;") conSyBase.Open() Dim cmdSyBase As New OleDb.OleDbCommand("MySQLStatement", conSyBase) Dim drSyBase As OleDb.OleDbDataReader = cmdSyBase.ExecuteReader Try While drSyBase.Read /*Do some stuff with the data here */ End While Catch ex As Exception NotifyError(ex, "Read failed.") Finally drSyBase.Close() conSyBase.Close() drSyBase.Dispose() cmdSyBase.Dispose() conSyBase.Dispose() End Try
我找到了答案!
前
drSyBase.Close()
我们需要调用Command对象的cancel方法
cmdSyBase.Cancel()
我相信这可能是特定于Sybase数据库的
自从我使用VB.NET已经有一段时间了,但是在Cis中使用" using"语句来处理此问题的最安全方法。
这就像一个隐式的try-catch,它可以确保在"使用"结束时所有资源都被关闭/取消和处置。
using (OleDb.OleDbConnection connection = new OleDb.OleDbConnection(connectionString)) { DoDataAccessStuff(); } // Your resource(s) are killed, disposed and all that
更新:在VB.NET 2.0中找到有关Using语句的链接,希望对我们有所帮助。
Using conSyBase As New OleDb.OleDbConnection("Provider=Sybase.ASEOLEDBProvider.2;Server Name=xx.xx.xx.xx;Server Port Address=5000;Initial Catalog=xxxxxxxxxx;User ID=xxxxxxxx;Password=xxxxxxxxx;"), _ cmdSyBase As New OleDb.OleDbCommand("MySQLStatement", conSyBase) conSyBase.Open() Dim drSyBase As OleDb.OleDbDataReader = cmdSyBase.ExecuteReader Try While drSyBase.Read() '...' End While Catch ex As Exception NotifyError(ex, "Read failed.") End Try cmdSyBase.Cancel() End Using