删除MS ACCESS DB的SQL语句

时间:2014-08-11 19:47:19

标签: vb.net ms-access

我正在尝试为MS Access DB运行删除语句,并且收到“索引超出范围的错误。必须是非负数且小于集合的大小”。

这是我的删除按钮代码:

Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
    ' This is our DELETE Statement. To be sure we delete the correct record and not all of   
    ' them.  
    ' We use the WHERE to be sure only that record that the user has selected is deleted.  
    Dim con1 As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Redirection\fakeout\Desktop\AccessDBs\MovieCatalog.mdb")
    Dim sqldelete As String
    sqldelete = "DELETE * FROM Table1 WHERE ID='" & dgvList.CurrentRow.Cells(7).Value.ToString & "'"
    ' This is our DataAdapter. This executes our SQL Statement above against the Database  
    ' we defined in the Connection String  
    Dim adapter As New OleDbDataAdapter(sqldelete, con1)
    ' Gets the records from the table and fills our adapter with those.  
    Dim dt As New DataTable("Table1")
    adapter.Fill(dt)
    ' Assigns the edited DataSource on the DataGridView and the refreshes the   
    ' view to ensure everything is up to date in real time.  
    dgvList.DataSource = dt
    ' This is a Sub in Module 1 to refresh the DataGridView when information is added,  
    '  updated, or deleted.  
    RefreshDGV()
End Sub

我在表单加载时打开我的连接:

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    sSql = "SELECT ID, Title, YearofFilm, Description, Field1 FROM Table1"
    LoadDS(sSql)
    FillGrid()
End Sub

Private Sub LoadDS(ByVal sSQL As String)
    Try
        Dim cnString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Redirection\fake\Desktop\AccessDBs\MovieCatalog.mdb"
        'Open Connection.
        Dim conn As OleDbConnection = New OleDbConnection(cnString)

        'Set the DataAdapter's query.
        da = New OleDbDataAdapter(sSQL, conn)
        ds = New DataSet()

        ' Fill the DataSet.
        da.Fill(ds, "Items")

        ' Set the source table.
        dtSource = ds.Tables("Items")
    Catch ex As Exception
        MessageBox.Show(ex.Message, "Error...", MessageBoxButtons.OK, MessageBoxIcon.Error)
    End Try
End Sub

我应该如何将其与删除功能结合使用?

1 个答案:

答案 0 :(得分:0)

您必须使用OleDbCommand对象将delete命令发送到数据库。您正在尝试使用检索数据的对象(即DataAdapter和DataTable)。

Using con1 As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Redirection\fakeout\Desktop\AccessDBs\MovieCatalog.mdb")

        Using cmd As New OleDbCommand("DELETE * FROM Table1 WHERE ID='" & dgvList.CurrentRow.Cells(7).Value.ToString & "'", con1)

            cmd.CommandType = CommandType.Text
            cmd.ExecuteNonQuery()

        End Using

    End Using