2013-01-15 68 views
0

依託自己在一個角落裏....關閉從打開的OLE DB連接的功能

用一塊的代碼,我發現在網絡上,不能弄清楚如何關閉此連接。處理後返回的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嘗試重新創建命令,然後關閉它一起。

真的可以在這個上使用一些幫助。

+0

爲什麼你需要返回的命令對象?對所有實現'IDisposable'的對象(如連接或命令)使用'using'語句,不要返回命令,而是返回你想要的數據(如'DataTable'或'List(Of CustomClass)') 。 –

+0

它從多個位置調用。當我開始編碼刪除speadsheet文件時,才成爲問題。具有完美意義,我會研究更新,不確定爲什麼網絡示例沒有這樣做。 – htm11h

回答

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