I have an SQL statement that saves a username into a MySQL database on phpmyadmin that works like a charm:
Dim SQLStatement As String = "INSERT INTO accountinfodb(`Usernames`) VALUES ('" & txtUsername.Text & "')"
However
I also ask for the users password, which I'd like to store as well, so I though this would make sense:
Dim SQLStatement As String = "INSERT INTO accountinfodb(`Usernames`, `Passwords`) VALUES ('" & txtUsername.Text & txtPasswd.Text & "')"
Unfortunately this code does not work, I get errors about a valid and open connection, or a syntax error in my MySQL syntax. So I was wondering if anyone knew the correct way to store the username and password into my DB?
Here is my FULL vb.net code.
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
EDIT 1
#Rahul
I added your SQL Statement to my code and I am given the following error when I input a random username/passwd
An unhandled exception of type 'MySql.Data.MySqlClient.MySqlException'
occurred in MySql.Data.dll
Additional information: You have an error in your SQL syntax; check
the manual that corresponds to your MariaDB server version for the
right syntax to use near 'test')' at line 1
Look at your SQL INSERT statement, it's missing a , comma in VALUES section
VALUES ('" & txtUsername.Text & txtPasswd.Text & "')
^... Here
Your statement should look like
"INSERT INTO accountinfodb(`Usernames`, `Passwords`)
VALUES ('" & txtUsername.Text & "','" & txtPasswd.Text & "')"
Edit:
I must mentioned that your current code is vulnerable to SQL Injection attack due to the fact that you are passing user input directly as concatenated values. You should rather use SqlParameter and pass those values as parameter instead accordingly. A sample would be
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())
Related
I have designed a login with registration web page in ASP.Net using VB.NET but I want the new user to first register his/her details and the details to be stored in a MySQL database.
I have created a database in MySQL. I am failing to connect my Registration form to the database in MySQL.
Can someone assist with the connection code for ASP.Net in VB.Net to MySQL database?
This is the code that i have done but it is giving me errors.
Imports MySql.Data
Imports System.IO
Public Class Registration
Inherits System.Web.UI.Page
Dim strConn = "Server=localhost;database=Login;Uid =root;Pwd=;"
Dim con As New MySqlClient.MySqlConnection
Dim cmd As New MySqlClient.MySqlCommand
Dim da As New MySqlClient.MySqlDataAdapter
Private Sub BtnSave_Click(sender As Object, e As EventArgs) Handles BtnSave.Click
Dim User_ID, First_Name, Last_Name, Email, Password As String
User_ID = TxtUserID.Text
First_Name = TxtFacultyName.Text
Last_Name = TxtLastName.Text
First_Name = TxtEmail.Text
First_Name = TxtPassword.Text
Dim cmdtxt As String = Nothing
cmdtxt = "Insert into Login(User_ID, First_Name, Last_Name, Email, Password ) " &
"Values('" & User_ID & "','" & First_Name & "', '" & Last_Name & "','" & Email & "','" & Password & "' ) "
Try
'The connection
con.ConnectionString = strConn
con.Open()
'The OLEDB Command
With cmd
.Connection = con
.CommandType = CommandType.Text
.CommandText = cmdtxt
End With
cmd.ExecuteNonQuery()
MsgBox("Registration Successful", MsgBoxStyle.Information, "Registration")
TxtUserID.Clear()
TxtFirstName.Clear()
TxtLastName.Clear()
TxtEmail.Clear()
TxtPassword.Clear()
Catch ex As Exception
MsgBox(ex.Message, vbCritical)
End Try
End Sub
End Class
As far as the connection string, see https://www.connectionstrings.com/mysql-connector-net-mysqlconnection/
Keep all your database objects local so you can be sure they are closed and disposed. Using...End Using blocks take care of this for you. You can pass the connection string directly to the constructor of the Connection. Likewise, you can pass the command text and the connection directly to the constructor of the Command.
Your UserID field should be an auto-number field (identity field) in the database. You do not include an auto-number fields in insert commands. For the other fields, use parameters to avoid Sql injection and make writing the sql statement easier. (no ampersands and double quotes and single quotes.
Open the connection at the last possible moment; right before the .Execute...
Imports MySql.Data.MySqlClient
Private Sub BtnSave_Click(sender As Object, e As EventArgs) Handles BtnSave.Click
Dim strSql = "Insert into Login(First_Name, Last_Name, Email, Password ) Values(#FName, #LName, #Email, #Password)"
Try
Using con As New MySqlConnection("Server=localhost;database=Login;Uid =root;Pwd=;"),
cmd As New MySqlCommand(strSql, con)
With cmd.Parameters
.Add("#FName", MySqlDbType.VarChar, 50).Value = TxtFacultyName.Text
.Add("#LName", MySqlDbType.VarChar, 50).Value = TxtLastName.Text
.Add("#Email", MySqlDbType.VarChar, 50).Value = TxtEmail.Text
.Add("#Password", MySqlDbType.VarChar, 50).Value = TxtPassword.Text
End With
con.Open()
cmd.ExecuteNonQuery()
End Using 'Closes and disposes the command and connection
MsgBox("Registration Successful", MsgBoxStyle.Information, "Registration")
TxtUserID.Clear()
TxtFirstName.Clear()
TxtLastName.Clear()
TxtEmail.Clear()
TxtPassword.Clear()
Catch ex As Exception
MsgBox(ex.Message, vbCritical)
End Try
End Sub
Finally, NEVER store passwords as plain text. I will leave it to you to research salting and hashing of passwords and add this to the code.
I am trying to make a little program that writes and reads from a Mysql database. The reading part is going well, but I am a bit stuck in the write part.
This is my code:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Absenden.Click
Dim conn As New MySqlConnection
Dim command As MySqlCommand
Dim myConnectionString As String
myConnectionString = "server=Nothing;uid=to;pwd=see;database=here;"
conn.ConnectionString = myConnectionString
Try
conn.Open()
Dim Querywrite As String
Querywrite = "select * FROM here.message INSERT INTO message admin='" & TB_Name.Text & "' and message='" & TB_Nachricht.Text & "' and Server='" & TB_Server.Text & "' and status='" & TB_Status.Text & "' "
command = New MySqlCommand(Querywrite, connection)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
conn.Close()
End Sub
The Querywrite part is the problem I think. The input comes from Textboxes in a Windows Form.
Thanks for your help!
Perhaps, if someone shows you once then you will get the idea. The main thing is to always use parameters; not only will you avoid minor sytax and type errors but you will avoid major disasters of malicious input. I guessed at the datatypes of your fields. Please check your database for the types and adjust your code accordingly.
Private Sub InsertData()
Dim strQuery As String = "Insert Into message (admin, message, Server, status) Values (#admin, #message, #Server, #status);"
Using cn As New MySqlConnection("your connection string")
Using cmd As New MySqlCommand With {
.Connection = cn,
.CommandType = CommandType.Text,
.CommandText = strQuery}
cmd.Parameters.Add("#admin", MySqlDbType.VarString).Value = TB_Name.Text
cmd.Parameters.Add("#message", MySqlDbType.VarString).Value = TB_Nachricht.Text
cmd.Parameters.Add("#Server", MySqlDbType.VarString).Value = TB_Server.Text
cmd.Parameters.Add("#status", MySqlDbType.VarString).Value = TB_Status.Text
cn.Open()
cmd.ExecuteNonQuery()
cn.Close()
End Using
End Using
End Sub
I am pretty sure I have all of my information right here, but I keep getting this error
http://puu.sh/qoZDQ/7294d6e682.png
The code I used: (Not mine)
I have the right username password and database name (I think)
'SET THE CONNECTION BETWEEN VISUAL BASIC AND MYSQL DATABASE
Dim con As SqlConnection = New SqlConnection("Data Source=mysql9.000webhost.com;" & "Initial Catalog=databasename;" & "User ID=username;" & "Password=password;")
'A SET OF COMMAND IN MYSQL
Dim cmd As New SqlCommand
'SET A CLASS THAT SERVES AS THE BRIDGE BETWEEN A DATASET AND DATABASE FOR SAVING AND RETRIEVING DATA.
Dim da As New SqlDataAdapter
'SET A CLASS THAT CONSISTS SPECIFIC TABLE IN THE DATABASE
Dim dt As New DataTable
Dim sqlQuery As String
Dim result As Integer
Private Sub register(ByVal sqlQuery As String)
Try
'OPENING THE CONNECTION
con.Open()
'HOLDS THE DATA TO BE EXECUTED
With cmd
.Connection = con
.CommandText = sqlQuery
End With
'EXECUTE THE DATA
Result = cmd.ExecuteNonQuery
'CHECKING IF THE DATA HAS BEEN EXECUTED OR NOT
If result > 0 Then
MsgBox("User has been registered.")
Else
MsgBox("Failed to register the user.")
End If
con.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub login(ByVal sqlQuery As String)
Try
con.Open()
With cmd
.Connection = con
.CommandText = sqlQuery
End With
'FILLING THE DATA IN A SPECIFIC TABLE OF THE DATABASE
da.SelectCommand = cmd
dt = New DataTable
da.Fill(dt)
'DECLARING AN INTEGER TO SET THE MAXROWS OF THE TABLE
Dim maxrow As Integer = dt.Rows.Count
'CHECKING IF THE DATA IS EXIST IN THE ROW OF THE TABLE
If maxrow > 0 Then
MsgBox("Welcome " & dt.Rows(0).Item(4))
Else
MsgBox("Account does not exist.")
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
con.Close()
End Sub
Private Sub btn_Register_Click(sender As Object, e As EventArgs) Handles btn_Register.Click
sqlQuery = "INSERT INTO `dbuser` ( `user_name`, `user_username`, `user_pass`, `user_type`, `user_steamid`)" & "VALUES ('" & txtname.Text & "','" & txtusername.Text & "','" & txtpassword.Text & "','" & cbotype.Text & "','" & txtsteamid.Text & "')"
register(sqlQuery)
End Sub
Private Sub btn_Login_Click(sender As Object, e As EventArgs) Handles btn_Login.Click
sqlQuery = "SELECT * FROM `dbuser` WHERE user_username ='" & txtusername.Text & "' AND user_pass = '" & txtpassword.Text & "'"
login(sqlQuery)
End Sub
I used the database info from here http://puu.sh/qoZXo/a391cba854.jpg (Also not my info just an example so I dont post my info publicly)
I fixed my issue with the help of what Plutonix commented
MySql is not the same thing as Microsoft SqlServer – Plutonix
So I did some googling and found this: https://dev.mysql.com/downloads/connector/net/
This is the .Net framework for MySql (I think thats the right terms)
anyhow installing this then changing the top line of my code from
imports System.Data.SqlClient
To:
imports MySql.Data.MySqlClient
and changing the sql variables in the code to MySql variables by just adding My to the first bit, and it seems to work "better" I now have a new issue, but its with 000webhosts mysql database, not the code.
I'm trying to hash the password the user enters into my DB as MD5, and I'm having trouble with it. I know MD5 is not as secure as it was before, and now not with salting, this is just for testing purposes and in no way am I actually deploying this for people to use. It's just for fun! The username gets entered into the database but the password doesn't. Here is my code:
Imports MySql.Data.MySqlClient
Imports System.Security.Cryptography
Imports System.Text
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 HashedPass As String = ""
'Converts the Password into bytes, computes the hash of those bytes, and then converts them into a Base64 string
Using MD5hash As MD5 = MD5.Create()
System.Convert.ToBase64String(MD5hash.ComputeHash(System.Text.Encoding.ASCII.GetBytes(txtPasswd.Text)))
End Using
Dim SQLStatement As String = "INSERT INTO accountinfodb(`Usernames`, `Passwords`) VALUES ('" & txtUsername.Text & "','" & HashedPass & "')"
SaveAccountInformation(SQLStatement)
MessageBox.Show("Account Successfully Registered")
frmLogin.Show()
frmLoginScreen.Hide()
Else
MessageBox.Show("Passwords Do Not Match!")
txtPasswd.Text = Focus()
txtPasswd.Clear()
txtPasswd2.Text = Focus()
txtPasswd2.Clear()
End If
End Sub
End Class
I think I possibly added the wrong value in my SQL Query, but if I add txtPasswd, I'm not sure where I'd put the HashedPass variable into my code?
The answer to your question is found with basically the same code here:
VB.NET login with a MySQL database
Direct link to answer:
https://stackoverflow.com/a/22939770/1475285
As mentioned by Bread102, you're not assigning the hash function result to your variable. The below should work in your case
Dim HashedPass As String = ""
Using MD5hash As MD5 = MD5.Create()
HashedPass = System.Convert.ToBase64String(MD5hash.ComputeHashSystem.Text.Encoding.ASCII.GetBytes(txtUsername.Text)))
End Using
Dim SQLStatement As String = "INSERT INTO accountinfodb(`Usernames`, `Passwords`) VALUES ('" & txtUsername.Text & "','" & HashedPass & "')"
Hi stackoverflow people!
I have been recently developing a simple vb.net program that connects to a mysql database to register and login users with given credentials. I have used this code to register my users but I keep getting and error (below the code)
Dim insertUser As String = "INSERT INTO users(ID, username, password, email, verif)" _
& " VALUES('','" & Username.Text & "','" & Password.Text & "','" & Email.Text & "','" & currentRandString & "');"
Dim checkUsername As String = "SELECT * FROM users WHERE username='" & Username.Text & "'"
MysqlConn = New MySqlConnection()
MysqlConn.ConnectionString = mysqlconntxt4reg
MysqlConn.Open()
Dim myCommand As New MySqlCommand
myCommand.Connection = MysqlConn
myCommand.CommandText = checkUsername
myAdapter.SelectCommand = myCommand
Dim myData As MySqlDataReader
myData = myCommand.ExecuteReader
If myData.HasRows > 0 Then
MsgBox("Username Already In Use...", MsgBoxStyle.Critical, "Error")
myData.Close()
Else
myData.Close()
Dim myCommand2 As New MySqlCommand
myCommand2.Connection = MysqlConn
myCommand2.CommandText = insertUser
myAdapter.SelectCommand = myCommand2
Dim myData2 As MySqlDataReader
myData2 = myCommand2.ExecuteReader
Mail(Email.Text, currentRandString)
Me.Close()
myData2.Close()
End If
Catch myerror As MySqlException
MsgBox("Error While Connecting To Database:" & vbNewLine & vbNewLine & myerror.ToString, MsgBoxStyle.Critical, "Error")
Finally
MysqlConn.Dispose()
End Try
I have closed all my datareaders before opening other ones so I do not see why this does not work...
Error:
Link to Error Image
I would appreciate any help on this topic!
Thanks
Rodit
I would use the using statement around all the disposable objects to be sure that they release every references to the connection when they are no more needed, but looking at your code, I think you don't need at all the datareaders because you could resolve your problem just with the commands
Dim insertUser As String = "INSERT INTO users(username, password, email, verif)" _
& " VALUES(#p1, #p2,#p3,#p4)"
Dim checkUsername As String = "SELECT COUNT(*) FROM users WHERE username=#p1"
Using MysqlConn = New MySqlConnection(mysqlconntxt4reg)
Using myCommand = New MySqlCommand(checkUsername, MysqlConn)
MysqlConn.Open()
myCommand.Parameters.AddWithValue("#p1", Username.Text)
Dim result = myCommand.ExecuteScalar()
if result IsNot Nothing AndAlso Convert.ToInt32(result) > 0 Then
MsgBox("Username Already In Use...", MsgBoxStyle.Critical, "Error")
Else
Using myCommand2 = New MySqlCommand(insertUser, MysqlConn)
mycommand2.Parameters.AddWithValue("#p1",Username.Text)
mycommand2.Parameters.AddWithValue("#p2",Password.Text )
mycommand2.Parameters.AddWithValue("#p3",Email.Text)
mycommand2.Parameters.AddWithValue("#p4",currentRandString )
myCommand2.ExecuteNonQuery()
Mail(Email.Text, currentRandString)
End Using
End If
End Using
End Using
Of course I have replaced your string concatenations with a parameterized query. This is really an important thing to do to avoid Sql Injection
I have replaced the query that checks the user existence with a scalar operation that can be used with the command ExecuteScalar. Also, in the first query, it seems that you try to insert the field ID with an empty string. I think that the first field (ID) is an autonumber field and, in this case, you don't add it to the insert query and don't pass any value because the database will calculate that field for you.