如何使用VB在SQL Server中按ID删除行

时间:2014-04-25 04:02:37

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

我正在使用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

2 个答案:

答案 0 :(得分: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语法言。

答案 1 :(得分:0)

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

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

使用`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