MySQL语句将密码保存到数据库?

时间:2016-01-16 22:08:30

标签: mysql sql vb.net

我有一个SQL语句,它将用户名保存到phpmyadmin上的MySQL数据库中,就像魅力一样:

Dim SQLStatement As String = "INSERT INTO accountinfodb(`Usernames`) VALUES ('" & txtUsername.Text & "')"

然而

我也要求用户密码,我也想存储,所以我觉得这很有意义:

Dim SQLStatement As String = "INSERT INTO accountinfodb(`Usernames`, `Passwords`) VALUES ('" & txtUsername.Text & txtPasswd.Text & "')"

不幸的是,这段代码不起作用,我收到有关有效和开放连接的错误,或MySQL语法中的语法错误。所以我想知道是否有人知道将用户名和密码存储到我的数据库的正确方法?

这是我的完整vb.net代码。

Imports MySql.Data.MySqlClient


Public Class frmSignup
Dim ServerString As String = "Server=localhost;User Id=root;Password=;Database=accountinfo"
Dim SQLConnection As MySqlConnection = New MySqlConnection

Private Sub Form3_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    SQLConnection.ConnectionString = ServerString

    Try
        If SQLConnection.State = ConnectionState.Closed Then
            SQLConnection.Open()
            MsgBox("Successfully connected to DB")

        Else
            SQLConnection.Close()
            MsgBox("Failed to connect to DB")
        End If
    Catch ex As Exception
        MsgBox(ex.ToString)

    End Try
End Sub

Public Sub SaveAccountInformation(ByRef SQLStatement As String)
    Dim cmd As MySqlCommand = New MySqlCommand

    With cmd
        .CommandText = SQLStatement
        .CommandType = CommandType.Text
        .Connection = SQLConnection
        .ExecuteNonQuery()
    End With
    SQLConnection.Close()
    SQLConnection.Dispose()
End Sub

Private Sub btnSignup_Click(sender As Object, e As EventArgs) Handles btnSignup.Click
    If txtPasswd.Text = txtPasswd2.Text Then
        MessageBox.Show("Passwords Match!")

        Dim SQLStatement As String = "INSERT INTO accountinfodb(`Usernames`, `Passwords`) VALUES ('" & txtUsername.Text & txtPasswd.Text & "')"
        SaveAccountInformation(SQLStatement)



        MessageBox.Show("Account Successfully Registered")
    Else
        MessageBox.Show("Passwords Do Not Match!")
        txtPasswd.Text = Focus()
        txtPasswd.Clear()
        txtPasswd2.Text = Focus()
        txtPasswd2.Clear()

    End If
End Sub
End Class

编辑1

@Rahul

我将SQL语句添加到我的代码中,当我输入随机用户名/密码时,我收到以下错误

  

“MySql.Data.MySqlClient.MySqlException”类型的未处理异常   发生在MySql.Data.dll

中      

其他信息:您的SQL语法有错误;校验   与您的MariaDB服务器版本对应的手册   在第1行的“test”附近使用正确的语法

1 个答案:

答案 0 :(得分:2)

查看您的SQL INSERT语句,它在,部分中缺少VALUES逗号

VALUES ('" & txtUsername.Text & txtPasswd.Text & "')
                             ^... Here

您的陈述应该是

"INSERT INTO accountinfodb(`Usernames`, `Passwords`) 
VALUES ('" & txtUsername.Text & "','" & txtPasswd.Text & "')"

修改 我必须提到您当前的代码容易受到SQL注入攻击,因为您将用户输入直接作为连接值传递。您应该使用SqlParameter并相应地将这些值作为参数传递。样本将是

Dim SQLStatement As String = "INSERT INTO accountinfodb(`Usernames`, `Passwords`) VALUES (@username, @password)"

    cmd.Parameters.AddWithValue("@username", txtUsername.Text.Trim())
    cmd.Parameters.AddWithValue("@password", txtPasswd.Text.Trim())