[英]MySQL statement to save password to Database?
我有一條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
@拉胡爾
我將您的SQL語句添加到了代碼中,輸入隨機的用戶名/密碼時出現以下錯誤
MySql.Data.dll中發生了類型為'MySql.Data.MySqlClient.MySqlException'的未處理異常
附加信息:您的SQL語法有錯誤; 檢查與您的MariaDB服務器版本相對應的手冊以在第1行的'test')'附近使用正確的語法
看看你的SQL INSERT
語句,它缺少一個,
以逗號VALUES
節
VALUES ('" & txtUsername.Text & txtPasswd.Text & "')
^... Here
您的陳述應如下所示
"INSERT INTO accountinfodb(`Usernames`, `Passwords`)
VALUES ('" & txtUsername.Text & "','" & txtPasswd.Text & "')"
編輯:我必須提到,由於您直接將用戶輸入作為串聯值傳遞,因此您當前的代碼容易受到SQL Injection攻擊。 您應該使用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())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.