2016-06-07 105 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