0

我试图在他/她注销时从数据库中删除用户名。我的代码如下,它不起作用。我认为它可能与连接字符串(数据库,密码)有关

Private Sub Button1_Click_1(sender As System.Object, e As System.EventArgs) Handles Button1.Click

    Dim Query As String
    Dim con As MySqlConnection = New MySqlConnection("Server=localhost;User ID=root;Password=*Mypassword*;Database=myusers")
    con.Open()
    Query = "Delete FROM users WHERE name  =" + loginuser.Text
    'Table = users
    'Name = Varchar(20)
    'loginuser.text = Name (username)
    Dim cmd As MySqlCommand = New MySqlCommand(Query, con)
    MsgBox(Query)
    Dim i As Integer = cmd.ExecuteNonQuery()
    If (i > 0) Then
        MsgBox("Record is Successfully Deleted")
    Else
        MsgBox("Record is not Deleted")
    End If
    con.Close()
End Sub
4

2 回答 2

1

您没有在 sql 字符串中用引号将名称值括起来,例如:Delete FROM users WHERE name = 'abcname'

更改您的代码以使用参数,这是一种干净且安全的方式来传递值,并且在使用字符串参数时您不必担心引号

Query = "Delete FROM users WHERE name  = @name"
Dim cmd As MySqlCommand = New MySqlCommand(Query, con)
MySqlCommand.Parameters.AddWithValue("@name",loginuser.Text)
于 2013-03-23T04:10:16.127 回答
0

字符串文字需要用单引号括起来,因此您的查询应该是:

Query = "Delete FROM users WHERE name  = '" + loginuser.Text + "'"

将字符串连接到 SQL 语句中也会使您面临 SQL 注入攻击(或者甚至只是考虑有人将“O'Brien”作为登录名)。您应该始终使用参数。

于 2013-03-23T04:07:22.610 回答