使用 MS Excel 驱动程序将工作表读入数据表时如何解决“太多客户端任务”错误

问题描述 投票:0回答:1

社区,

我从该线程获取了一些 VB 代码,以便将工作表内容读入数据表。

文字

Public Shared Function ReadExcelIntoDataTable(ByVal FileName As String, ByVal SheetName As String) As DataTable
    Dim RetVal As New DataTable
    Dim strConnString As String
    strConnString = "Driver={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};DBQ=" & FileName & ";"

    Dim strSQL As String 
    strSQL = "SELECT * FROM [" & SheetName & "$]"

    Dim y As New Odbc.OdbcDataAdapter(strSQL, strConnString)
    y.Fill(RetVal)

    Return RetVal
End Function

该代码在前 3-4 次使用中可以正常工作,但随后会出现此错误:

错误 [08004] [Microsoft][ODBC Excel 驱动程序] 客户端任务太多。

<< IMAGE HERE >> enter image description here

我必须退出/重新启动应用程序才能继续开发。大约四次运行后,错误再次出现,我必须重新启动应用程序。

我的结论是连接没有关闭,因此导致“客户端任务过多”。对错误消息的搜索还表明存在关闭连接的问题。

任何有关如何更改代码以防止错误的建议将不胜感激。

问候, 杰瑞

研究错误消息无助于确定关闭连接的任何特定方法。

excel vb.net datatable driver connect
1个回答
0
投票

看起来这是一个常见问题的新表现。

OdbcDataAdapter
实现
IDisposable
(间接地,在基类中的几个级别上)。每当你使用实现
IDisposable
的东西时,这是一个信号,当你完成它时,你必须调用 Dispose
。通常是因为某种资源分配需要释放。

在这种情况下,正确的做法是使用

Using

 块,它会在退出块时为您调用 
Dispose
(并且还要确保即使在发生异常时也会发生这种情况) ):

Using y = New Odbc.OdbcDataAdapter(strSQL, strConnString) y.Fill(RetVal) End Using
    
© www.soinside.com 2019 - 2024. All rights reserved.