[英]VB.Net Delete Selected Row in DataGridView MySql
This the code that I use. 这是我使用的代码。 The message box is appearing but when I select yes, the selected row is not deleted at the datagridview and database.
出现消息框,但是当我选择“是”时,不会在datagridview和数据库中删除所选行。
Private Sub Delete2_Click_1(sender As Object, e As EventArgs) Handles Delete2.Click
MySqlConn = New MySqlConnection
MySqlConn.ConnectionString = "server=127.0.0.1;userid=root;password=;database=equipment"
Try
If Me.DataGridView2.Rows.Count > 0 Then
If Me.DataGridView2.SelectedRows.Count > 0 Then
Dim intStdID As Char = Me.DataGridView2.SelectedRows(0).Cells("asset_code").Value
'open connection
If Not MySqlConn.State = ConnectionState.Open Then
MySqlConn.Open()
End If
'delete data
Dim cmd As New MySqlCommand
cmd.Connection = MySqlConn
cmd.CommandText = "DELETE * FROM equipment.equipment" & intStdID
Dim res As DialogResult
res = MsgBox("Are you sure you want to DELETE the selected Row?", MessageBoxButtons.YesNo)
If res = Windows.Forms.DialogResult.Yes Then
cmd.ExecuteNonQuery()
Else : Exit Sub
End If
'refresh data
Load_table()
'close connection
MySqlConn.Close()
End If
End If
Catch ex As MySqlException
End Try
Look at this line: 看这行:
cmd.CommandText = "DELETE * FROM equipment.equipment" & intStdID
It attempts to append the ID value from the selected cell to the SQL statement. 它尝试将ID值从选定的单元格追加到SQL语句。 However, it seems like this is just the ID value.
但是,这似乎只是 ID值。 You also need the
WHERE ID=
portion for the query. 您还需要查询的
WHERE ID=
部分。
Moreover, it's using this ID value in the query in the wrong way . 此外,它以错误的方式在查询中使用此ID值。 It's NEVER okay to use string concatenation to include data in a query.
使用字符串连接在查询中包含数据永远是不可能的。 You must use parameterized queries.
您必须使用参数化查询。
The code below demonstrates this, as well as several other better patterns for this method, with the caveat that I had to guess as some names and types from your database. 下面的代码演示了此方法以及该方法的其他几种更好的模式,但有一些警告,我不得不猜测是数据库中的某些名称和类型。
Private Sub Delete2_Click_1(sender As Object, e As EventArgs) Handles Delete2.Click
If Me.DataGridView2.Rows.Count = 0 OrElse Me.DataGridView2.SelectedRows.Count = 0 Then
Exit Sub
End If
Dim res As DialogResult = MsgBox("Are you sure you want to DELETE the selected Row?", MessageBoxButtons.YesNo)
If res <> DialogResult.Yes Then Exit Sub
Dim intStdID As Char = Me.DataGridView2.SelectedRows(0).Cells("asset_code").Value
Dim SQL as String = "DELETE * FROM equipment.equipment WHERE equipment.StdID= @AssetCode"
Using con As New MySqlConnection("server=127.0.0.1;userid=root;password=;database=equipment"), _
cmd As New MySqlCommand(SQL, con)
cmd.Parameters.Add("@AssetCode", MySqlDbType.VarChar, 1).Value = intStdID
con.Open()
cmd.ExecuteNonQuery()
End Using
Load_table()
End Sub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.