关闭从函数内打开的OLE DB连接

时间:2013-01-15 21:47:56

标签: vb.net ole oledbcommand

支持自己在一个角落......

使用我在网络上找到的一段代码,无法弄清楚如何关闭此连接。返回的OleDbcommand objCommand在处理后仍保持打开状态。我需要将其关闭,以便在从中提取数据后删除该文件。 (不要让他们在服务器上闲逛。)

这比我尝试过的100行代码要简单得多。此功能打开连接。

Protected Function ExcelConnection() As OleDbCommand
    Dim fileName As String = Session("newUploadedFile")

    ' Connect to the Excel Spreadsheet
    Dim xConnStr As String = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
          "Data Source=" & Server.MapPath(String.Format("~/Upload/{0}", fileName)) & ";" & _
          "Extended Properties=Excel 8.0;"

    ' create your excel connection object using the connection string
    Dim objXConn As New OleDbConnection(xConnStr)
    objXConn.Open()
    ' use a SQL Select command to retrieve the data from the Excel Spreadsheet
    ' the "table name" is the name of the worksheet within the spreadsheet
    ' in this case, the worksheet name is "Sheet1" and is expressed as: [Sheet1$]

    Dim objCommand As New OleDbCommand("SELECT Name FROM [Sheet1$]", objXConn)

    Return objCommand
End Function

我试过......

  ExcelConnection.connection.close()

以及大约40次尝试重新创建Command然后关闭它。

真的可以在这个上使用一些帮助。

1 个答案:

答案 0 :(得分:1)

这可能不是执行此操作的最佳方法,但如果您真的必须这样做,请考虑在调用例程中定义和打开连接,并将其作为参数传递给此例程。然后它可以在呼叫路由中关闭,因此......

Sub Main()

    Dim xConnStr As String = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
        "Data Source=" & Server.MapPath(String.Format("~/Upload/{0}", fileName)) & ";" & _
        "Extended Properties=Excel 8.0;"

    Dim objXConn As New OleDbConnection(xConnStr)
    objXConn.Open()
    Dim ObjCommand As New OleDbCommand = ExcelConnection(objXConn)

    'Whatever other operations you want to do with your returned OleDbCommand
    ...

    objXConn.Close()

End Sub

Function ExcelConnection(PassedConnection As OleDbConnection) As OleDbCommand
    Dim fileName As String = Session("newUploadedFile")
    Dim objCommand As New OleDbCommand("SELECT Name FROM [Sheet1$]", PassedConnection)
    Return objCommand
End Function

我在这里贴了类似的东西...... Best fastest way to read an Excel sheet