2016-06-07 77 views
0

我試圖超載TableAdapter(approach)的「刪除」方法。如何從'here'執行SQL語句來處理刪除?自定義TableAdapter刪除方法覆蓋

我有:

Namespace AFL_BackendDataSetTableAdapters 

    Partial Class Log_entry_unitTableAdapter 

     Public Overloads Function Delete(ByVal LogEntryID As Integer) As Integer 

      Dim SQL As String 

      SQL = "DELETE FROM log_entry_unit WHERE log_entry_unit_id=" & LogEntryID 

      '?????.Execute SQL 

      Return 0 

     End Function 

    End Class 

End Namespace 

超載工作正常,但我不知道該怎麼做最困難的部分,實際上從這裏操縱數據。以前,我剛剛進入數據集設計器並手動更新生成的方法以像我希望的那樣工作,但每當使用嚮導重新生成數據集時,(如預期的那樣)將被覆蓋。

我以前只使用生成的方法操縱數據,現在我卡住了。

編輯的基於W /下面這裏威廉的幫助下最終答案 是最終的工作溶液(注意:我不得不使用OleDb的,而不是SQL,因爲我的數據集是訪問:

Imports System.Data.OleDb 

Namespace AFL_BackendDataSetTableAdapters 

    Partial Class Log_entry_unitTableAdapter 

     Public Overloads Function Delete(ByVal LogEntryID As Integer) As Integer 

      Dim queryString As String = "DELETE FROM log_entry_unit WHERE log_entry_unit_id=" & LogEntryID 
      Dim command As New OleDbCommand(queryString, Connection) 
      Dim r As Integer 

      Try 
       Connection.Open() 
       r = command.ExecuteNonQuery() 
      Catch ex As Exception 
       MsgBox(ex.Message) 
       r = 0 
      Finally 
       Connection.Close()     
      End Try 

      Return r 

     End Function 

    End Class 

End Namespace 

回答

0

我硬編碼的連接。串僅供參考這應該是在配置文件中作爲一個例子:

Dim connectionString As String = _ 
     "Data Source=(local);Initial Catalog=YourDatabase;" _ 
     & "Integrated Security=true" 

    Dim queryString As String = "DELETE FROM log_entry_unit WHERE log_entry_unit_id=" & LogEntryID 

    ' Create and open the connection in a using block. This 
    ' ensures that all resources will be closed and disposed 
    ' when the code exits. 
    Using connection As New SqlConnection(connectionString) 

     ' Create the Command 
     Dim command As New SqlCommand(queryString, connection) 

     ' Open the connection in a try/catch block. 
     Try 
      connection.Open() 
      command.ExecuteNonQuery() 
     Catch ex As Exception 
      ' handle exception here 
     End Try 
    End Using 

EDIT

我可能應該提到你可能會希望在刪除後再次填充你的適配器。

+0

這個答案確實不相關,因爲它不會修改現有的表格適配器。 – jmcilhinney

+0

@jmcilhinney我不同意。這是相關的。您仍然需要ADO.NET代碼。刪除後,他們應該再次填充適配器。也許這應該包含在答案中。 –

+0

這在概念上是我一直在尋找的。我不需要更新現有的表格adapater,因爲我想在此方法之外執行此操作。這是一個訪問連接,所以我認爲我需要使用OleDb而不是SqlConnection,但從我的第一眼看來,它看起來就像是一樣的事情。如果我卡住了,我會開一個新的問題。謝謝! – BrINClHOF