如何使用VB.NET在SQL中删除一行

huangapple go评论74阅读模式
英文:

How to delete a row in sql using vb.net

问题

抱歉,如果这很简单或基础的话,我是全新接触SQL和表格,所以我只是试着弄清楚它。

基本上,我正在尝试删除用户选择的一行,通过让他们点击一行,然后点击一个删除按钮,但我不知道它应该看起来如何。我尝试了几种不同的方法,但似乎都不起作用。没有错误出现,但它就是不会删除这行。

Private Sub DeleteSelectedUsers()
    Dim connection As SqlConnection = New SqlConnection()
    connection.ConnectionString = "Data Source=GERARD-PC\SQLEXPRESS; Initial Catalog=TestDB;User ID=AccountsUser;Password=password123"

    connection.Open()

    Dim adp As SqlDataAdapter = New SqlDataAdapter _
    ("Delete * from dgrdUsers.SelectedRows(0).Cells", connection)
End Sub

Private Sub btnDelete_Click(sender As Object, e As EventArgs) Handles btnDelete.Click
    Try
        Dim username As String = dgrdUsers.SelectedRows(0).Cells.Item("Username").Value.ToString()

        If (MessageBox.Show(Me, "Do you want to delete user " & username & "?", "Confirm Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = DialogResult.Yes) Then
            DeleteSelectedUsers()
        End If
    Catch ex As Exception

    End Try
End Sub

有任何想法吗?

英文:

Sorry if its easy or basic i am brand new to sql and tables so im just trying to figure it out
Basically im trying to delete a row that the user selects
By having them click on a row then clicking a delete button but i don't know how that should look ive tried a few different ways but none of them seem to work.
No error comes up but it just dosen't delete the row

 Private Sub DeleteSelectedUsers()
    Dim connection As SqlConnection = New SqlConnection()
    connection.ConnectionString = "Data Source=GERARD-PC\SQLEXPRESS; Initial Catalog=TestDB;User ID=AccountsUser;Password=password123"

    connection.Open()

    Dim adp As SqlDataAdapter = New SqlDataAdapter _
    ("Delete * from dgrdUsers.SelectedRows(0).Cells", connection)




End Sub
Private Sub btnDelete_Click(sender As Object, e As EventArgs) Handles btnDelete.Click
    Try

        Dim username As String = dgrdUsers.SelectedRows(0).Cells.Item("Username").Value.ToString()

        If (MessageBox.Show(Me, "Do you want to delete user " & username & "?", "Confirm Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = DialogResult.Yes) Then
            DeleteSelectedUsers()
        End If
    Catch ex As Exception

    End Try
End Sub

Any ideas?

答案1

得分: 2

删除数据库表中的行所需的语法至少包括三个部分。

  • DELETE 命令
  • FROM 语句,用于指定要执行删除操作的表
  • WHERE 条件,用于标识要删除的记录(或记录)

因此,它是一个类似于这样的字符串:DELETE FROM 表名 WHERE 条件
将其应用于您的代码,您会得到如下结果。

Private Sub DeleteSelectedUsers(userName as String)
    Using connection As SqlConnection = New SqlConnection()
       connection.ConnectionString = "...."
       connection.Open()
       Dim cmd As SqlCommand = New SqlCommand _
          ("DELETE FROM 表 WHERE userName = @user", connection)
       cmd.Parameters.Add("@user", SqlDbType.NVarChar).Value = userName
       cmd.ExecuteNonQuery()
   End Using
End Sub

(表和UserName是虚构的名称,因为我们不知道您的数据库的实际架构)

我所做的其他更改:

  • 连接是在 using 块内创建的,以确保在发生错误时也会发生适当的关闭和释放
  • 要删除的用户的名称应作为参数传递给函数
  • 当您只需要执行单个 SqlCommand 时,无需使用适配器
  • 查询不会连接字符串来构建命令,而是使用添加到命令本身的参数,并指定与数据库表上的类型匹配的数据类型
英文:

The syntax required to delete a row in the database table requires at least three parts.

  • The DELETE command
  • The FROM statement to identify the table where the delete action should occur
  • The WHERE condition to identify the record (or records) to delete

So it is a string like this: DELETE FROM tablename WHERE condition
and applied to your code you get this.

Private Sub DeleteSelectedUsers(userName as String)
    Using connection As SqlConnection = New SqlConnection()
       connection.ConnectionString = "...."
       connection.Open()
       Dim cmd As SqlCommand = New SqlCommand _
          ("DELETE FROM Table WHERE userName = @user", connection)
       cmd.Parameters.Add("@user", SqlDbType.NVarChar).Value = userName
       cmd.ExecuteNonQuery()
   End Using
End Sub

(Table and UserName are fantasy names because we don't know what is the actual schema of your database)

Other things I have changed:

  • The connection is created inside a using block to be sure a proper
    closure and dispose happens even in case of errors
  • The name of the user to remove should be passed as parameter to the
    function
  • No need to use an adapter when you just need to execute a single
    SqlCommand
  • The query doesn't concatenate strings to build the command but use a
    parameter added to the command itself and specifying a type for the
    data matching the type on the database table

huangapple
  • 本文由 发表于 2023年2月8日 18:03:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/75384128.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定