尝试从visual basic studio 2010中的访问数据库中删除记录

时间:2014-12-02 08:14:36

标签: vb.net visual-studio-2010 oledbcommand oledbdataadapter

Private Function CreatePlayerAdapter(ByVal playerDBconnection As OleDbConnection) As OleDbDataAdapter

//启动函数的实例

    Dim dataAdapter As OleDbDataAdapter = New OleDbDataAdapter()
    Dim myCommand As OleDbCommand
    Dim parameter As OleDbParameter

//建立字符串以告知从哪里删除记录以及如何找到我想要的记录。 // PlayerIDTextBox.Text是一个表单上的文本,它在选择名称列表后从数据库中填充(这可以正常工作)//连接已经打开并被定向到正确的位置

    Dim sql As String = "DELETE * FROM Players WHERE ID ='" & CInt(PlayerIDTextBox.Text) & "'"
    myCommand = New OleDbCommand(sql, playerDBconnection)

    parameter = myCommand.Parameters.Add("ID", OleDbType.Char, 3, "ID")
    parameter.SourceVersion = DataRowVersion.Original

    dataAdapter.DeleteCommand = myCommand

    Return dataAdapter
End Function

//执行按钮点击后调用此函数。 //ListPlayerComboBox.Text填充了名称,需要一个名称来填充PlayerIDTextBox.Text(正常工作)

Private Sub RemovePlayerButton_Click(sender As System.Object, e As System.EventArgs) Handles RemovePlayerButton.Click

        If ListPlayerComboBox.Text = " " Then
            MsgBox("Please Select a Player.")
    Else


        Me.CreatePlayerAdapter(playerDBConnection)

        End If


End Sub

//没有错误发生。但是,数据库中没有任何操作。请帮忙吗?

1 个答案:

答案 0 :(得分:0)

注意:

1)永远不要离开OleDbConnection Open。只有在你真正需要它时才允许它打开。这将使您免于以后的许多麻烦。原因可以在following stackoverflow question上找到。

2)如果您不打算使用它,则没有理由退回OleDbDataAdapter

3)正确使用您的参数:见下面的示例2

4)请注意restricted keywords中有一些Access。 Luckely为你ID不是一个。可以在此处找到restrictedKeywords:Keywords

我可能在这里错过了一些其他观点。任何人都可以自由添加em。


为什么不将Function CreatePlayerAdapter调整为以下内容:

1)没有参数

Private Sub CreatePlayerAdapter(ByVal playerDBconnection As OleDbConnection) 

    Dim myCommand As OleDbCommand

    Dim sql As String = "DELETE * FROM Players WHERE ID =" & CInt(PlayerIDTextBox.Text) 
    myCommand = New OleDbCommand(sql, playerDBconnection)

    playerDBconnection.Open()
    myCommand.ExecuteNonQuery()
    playerDBconnection.Close()
End Sub

2)带参数

Private Sub CreatePlayerAdapter(ByVal playerDBconnection As OleDbConnection) 

    Dim myCommand As OleDbCommand

    Dim sql As String = "DELETE * FROM Players WHERE ID = @playerId"
    myCommand = New OleDbCommand(sql, playerDBconnection)


    Dim param As New OleDb.OleDbParameter(@playerId", CInt(PlayerIDTextBox.Text))
    myCommand.Add(param)

    playerDBconnection.Open()
    myCommand.ExecuteNonQuery()
    playerDBconnection.Close()
End Sub

方法ExecuteNonQuery executes the query传递给命令on the specified OleDbConnection并返回受影响的行数。更多信息Here