不从数据库中删除
Posted
技术标签:
【中文标题】不从数据库中删除【英文标题】:Not removing from database 【发布时间】:2022-01-07 01:37:23 【问题描述】:我的代码没有从数据库中删除任何行。这些行显示在表单的列表视图中。它们可以从表单的列表视图中删除和消失,但不会从数据库表中删除。
另外,我使用 MS Access 作为数据库。
这是代码
Public Sub DeleteProduct()
If ListView1.SelectedIndices.Count <= 0 Then
Return
End If
Dim ItemNo As Integer = ListView1.SelectedIndices(0)
Try
Dim I As Integer = MsgBox("Are you sure you want to delete this record? You can't Undo", MsgBoxStyle.YesNo, "Are you sure?")
If I = MsgBoxResult.Yes Then
conn.Open()
Dim cmd2 As New OleDb.OleDbCommand("DELETE FROM PRODUCT WHERE product_id = '" & ListView1.Items(ItemNo).SubItems(0).Text & "'", conn)
cmd2.ExecuteNonQuery()
MsgBox("Record removed successfully", MsgBoxStyle.OkOnly, "Remove Succeeded")
Else
Return
End If
Catch ex As Exception
MsgBox(ex.Message)
Finally
conn.Close()
End Try
Refresh()
End Sub
【问题讨论】:
使用参数 - 否则.Text
属性中的撇号会破坏一切。
MsgBox("Record removed successfully"
ExecuteNonQuery first 的返回值来验证是否删除了一行,而不是简单地假设它是成功的。
无关:您是否考虑过实施软删除?这样您可以撤消删除。
很可能,ListView1.Items(ItemNo).SubItems(0).Text
不包含您期望的值,或者product_id
是一个数字,而不是文本。
如果有任何问题请分享错误信息。
【参考方案1】:
将用户界面代码与数据库代码分开。
连接和命令需要调用 Dispose
方法,因此它们应该在 Using 块中本地声明。养成使用Parameters而不是连接字符串来构建sql语句的习惯。
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If ListView1.SelectedIndices.Count = 0 Then
MessageBox.Show("You must select an item to delete.")
Exit Sub
End If
If MessageBox.Show("Are you sure you want to delete this record? You can't Undo", "Are you sure?", MessageBoxButtons.YesNo) = DialogResult.Yes Then
Dim ItemNo As Integer = ListView1.SelectedIndices(0)
Dim ProductID = CInt(ListView1.Items(ItemNo).Text)
Dim RecordsDeleted As Integer
Try
RecordsDeleted = DeleteProduct(ProductID)
Catch ex As Exception
MsgBox(ex.Message)
Exit Sub
End Try
If RecordsDeleted = 1 Then
MessageBox.Show("Record removed successfully", "Remove Succeeded")
ListView1.Items.RemoveAt(ItemNo)
Else
MessageBox.Show("Record was not deleter")
End If
End If
End Sub
Private OPConStr As String = "Your connection string."
Public Function DeleteProduct(ID As Integer) As Integer
Dim retval As Integer
Using conn As New OleDbConnection(OPConStr),
cmd As New OleDbCommand("DELETE FROM PRODUCT WHERE product_id = @ID", conn)
cmd.Parameters.Add("@ID", OleDbType.Integer).Value = ID
conn.Open()
retval = cmd.ExecuteNonQuery
End Using
Return retval
End Function
【讨论】:
谢谢你,但它显示了一个错误,上面写着“System.InvalidCastException:'从字符串'Snacks'转换为'Integer'类型无效。'”在“Dim ProductID = CInt”的一部分(ListView1.Items(ItemNo).Text)" 通常 ID 字段是一个数字。您确定要删除所有属于“零食”的项目吗?什么是主键?它是否显示在 ListView 中?要删除单个记录,您需要主键来唯一标识该记录。以上是关于不从数据库中删除的主要内容,如果未能解决你的问题,请参考以下文章