【问题标题】:Deleting SQL Database Rows in vb在 vb 中删除 SQL 数据库行
【发布时间】:2015-04-20 15:17:09
【问题描述】:

我在删除 SQL 数据库行以供下次删除时遇到问题。 第一次,它工作正常,但第二次,我收到错误消息(命令参数 [1] 无效)。

我使用 datagridview 来选择我想要删除的行(单/多)。 这是我的代码:

    Dim response As MsgBoxResult
    Dim i As Integer
    i = DataGridView1.CurrentRow.Index

    If Not Trim(DataGridView1.Item("Group", i).Value.ToString) = "Admin" Then
        response = MsgBox("Do you want remove this account ?" & vbNewLine & "Account : " & Trim(DataGridView1.Item("Name", i).Value.ToString), _
                          MsgBoxStyle.Question + MsgBoxStyle.YesNo, "Delete Data")
        If response = MsgBoxResult.Yes Then
            If Not MyConnection.State = ConnectionState.Open Then
                MyConnection.Open()
            End If
            cmd.Connection = MyConnection
            cmd.CommandText = "DELETE FROM t_User WHERE ID =?"
            cmd.Parameters.AddWithValue("@row", 0)
           For Each UserRow As DataGridViewRow In DataGridView1.SelectedRows
            If Not MyConnection.State = ConnectionState.Open Then
                    MyConnection.Open()
            End If
                cmd.Connection = MyConnection
                cmd.Parameters("@row").Value = UserRow.Cells("ID").Value
                DataGridView1.Rows.Remove(UserRow)
                cmd.ExecuteNonQuery()
                DeleteColumns()
                CreateColumns()
                MyConnection.Close()
           Next UserRow
            Me.BackgroundWorker1.RunWorkerAsync()
        End If
    End If

请帮助我,非常感谢您的帮助

【问题讨论】:

    标签: sql-server vb.net visual-studio-2010 visual-studio-2012 vbscript


    【解决方案1】:

    不要在 for 循环中关闭连接。移动这一行:

     MyConnection.Close()
    

    在 Next UserRow 行之后。

    或者,如果您确实需要在每一行之后重新打开连接 [这是不常见的],那么您需要像

    一样重做完整的 cmd
                cmd.Connection = MyConnection
                cmd.CommandText = "DELETE FROM t_User WHERE ID =?"
                cmd.Parameters.AddWithValue("@row", 0)
    

    【讨论】:

    • 我试过放在那里,但是当我尝试逐行/多行删除时问题是一样的
    • 尽量不要重新设置连接,去掉:cmd.Connection = MyConnection
    • 仍然是同样的问题,当我删除该行时(cmd.Connection = MyConnection)
    • 您是否使用调试器检查了 id 的值是否正确?
    猜你喜欢
    • 2014-05-09
    • 2020-08-03
    • 2015-04-08
    • 2015-02-15
    • 2014-04-03
    • 2020-03-12
    • 2019-06-23
    • 2017-06-27
    • 1970-01-01
    相关资源
    最近更新 更多