自定义TableAdapter删除方法覆盖

时间:2016-06-07 21:15:07

标签: vb.net ado.net

我正在尝试重载TableAdapter(approach)的“Delete”方法。如何从'here'执行SQL语句来处理删除?

我有:

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

重载工作正常,但我不知道如何处理困难部分并实际操作此处的数据。以前,我刚进入数据集设计器并手动更新生成的方法,就像我想要的那样工作,但每当我使用向导重新生成数据集时,(如预期的那样)都会被覆盖。

我以前只使用生成的方法操纵数据,现在我被卡住了。

编辑/最终答案 基于William的帮助,这里是最终的工作解决方案(注意我只需要使用OleDb而不是SQL,因为我的数据集是Access:

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

1 个答案:

答案 0 :(得分: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

修改

我可能应该提到你可能想在删除后再次填充你的适配器。