【问题标题】:How to delete rows by ID in SQL Server using VB如何使用VB在SQL Server中按ID删除行
【发布时间】:2014-06-10 15:02:28
【问题描述】:

我将 Microsoft Visual Studio 2010 和 SQL Server 2005 与 Management Studio 一起使用。 而且我是这种编程语言的新手。

这是我的代码:

Private Sub Delete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Delete.Click
    If MessageBox.Show("Do you really want to delete this record?", "Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) = DialogResult.No Then
        MsgBox("Operation cancelled")
    Else : Try
            Dim Command As New SqlCommand
            Dim con As SqlConnection = New SqlConnection("Server=HPC-107;Database=MRPdb;integrated security=sspi;...")
            con.Open()
            Command.CommandText = "DELETE * FROM dbo.inhouse_hardware_marterfile_tbl WHERE Equip_No ='" & (Equip_No.Text) & "'"
            Command.Connection = con
            Command.ExecuteNonQuery()
            con.Close()

        Catch ex As Exception
        End Try

        Exit Sub
    End If
End Sub

每当我运行它时,我都无法得到任何结果。任何帮助表示赞赏。谢谢! :D

【问题讨论】:

  • 可能你有一个例外。您可以尝试在您的 catch 块中添加异常日志记录吗?
  • 仔细考虑如果有人在您的 Equip_No 字段中输入 ';DROP TABLE inhouse_hardware_marterfile_tbl;-- 会发生什么。
  • 另外,在线发布您的 sa 密码不是一个好主意。
  • 这是在 Visual Studio 中调试的指南。如果你调试你的代码,你可以单步调试,看看问题出在哪里。 msdn.microsoft.com/en-us/library/sc65sadd(v=vs.80).aspx 最明显的问题是没有报告任何捕获的错误——你没有错误处理,你有错误抑制。

标签: sql vb.net sql-server-2005


【解决方案1】:
Private Sub Delete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Delete.Click
    If MessageBox.Show("Do you really want to delete this record?", "Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) = DialogResult.No Then
        MsgBox("Operation cancelled")
        Exit Sub
    End If

    Using con As New SqlConnection("Server=HPC-107;Database=MRPdb;integrated security=sspi;"), _
          cmd As New SqlCommand("DELETE dbo.inhouse_hardware_marterfile_tbl WHERE Equip_No = @EquipNo", con)

        'Had to guess at the column length here
        cmd.Parameters.Add("@EquipNo", SqlDbType.NVarChar, 10).Value = Equip_No.Text

        con.Open()
        Command.ExecuteNonQuery()
    End Using
End Sub

这修复了原始代码中的一些问题:一个大范围的 sql 注入漏洞,由于在抛出异常时无法保证关闭连接而导致拒绝服务的可能性,它修复了删除的 sql 语法声明。

【讨论】:

  • 它仍然没有在我的数据库中的表中显示结果。
【解决方案2】:

最好使用带参数的 SQL 命令。您的代码没有清理 Equip_No.Text 中的数据,这可能导致 SQL 注入。

使用 SQL Profiler 查看正在执行的语句。是否调用了删除函数?身份证有错吗?是否有一个您没有看到的异常被抛出,因为您没有重新抛出错误?

使用`Using' 语句保证连接关闭,即使出现错误:

Using con As New SqlConnection("Server=HPC-107;Database=MRPdb;integrated security=sspi;Uid=sa;Pwd=hochengtest;Trusted_Connection=no;") 
        con.Open()
        Command.CommandText = "DELETE * FROM dbo.inhouse_hardware_marterfile_tbl WHERE Equip_No ='" & (Equip_No.Text) & "'"
        Command.Connection = con
        Command.ExecuteNonQuery()
End Using

【讨论】:

  • DELETE * FROM ... 会导致 SQL 语法错误
猜你喜欢
  • 2021-02-27
  • 2014-12-10
  • 2013-05-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-09
  • 1970-01-01
相关资源
最近更新 更多