我试图在他/她注销时从数据库中删除用户名。我的代码如下,不起作用。我认为它可能与连接字符串(数据库,密码事物)
有关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
答案 0 :(得分: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)
答案 1 :(得分:-1)
字符串文字需要用单引号括起来,所以你的查询应该是:
Query = "Delete FROM users WHERE name = '" + loginuser.Text + "'"
将字符串连接到SQL语句中会打开SQL注入攻击(甚至只是想到有人将“O'Brien”作为登录名)。你应该总是使用参数。