VB.net Login with MySQL - mysql

I do not know what went wrong. Im new to vb. Can someone help me? Maybe correct my codes cause I've been spending so much time with this login form of mine. Thanks! here's my code.
By the way, I have a table with 3 columns. Username, Password and Privilege. Whenever I input my Login credentials, it only display the Msgbox Try again.
Imports MySql.Data.MySqlClient
Public Class LoginForm
Dim cn As New MySqlConnection
Dim cmd As MySqlCommand
Dim reader As MySqlDataAdapter
Private Sub OK_Click(sender As Object, e As EventArgs) Handles OK.Click
Dim tblUser As New DataTable
Try
If PasswordTextBox.Text = "" Or UsernameTextBox.Text = "" Then
MessageBox.Show("Please provide your login credentials!")
Else
Dim sql As String
sql = "SELECT * from user_account where username = '" & UsernameTextBox.Text & "' and password = '" & PasswordTextBox.Text & "'"
Using con As New MySqlConnection(My.Settings.ConnectionString)
With cmd
.Connection = con
.CommandText = sql
End With
reader.SelectCommand = cmd
reader.Fill(tblUser)
If tblUser.Rows.Count > 0 Then
Dim userType As String
userType = tblUser.Rows(0).Item(2)
If userType = "admin" Then
MsgBox("Welcome, Admin!")
frmAdminMain.Show()
ElseIf userType = "encoder" Then
MsgBox("Welcome, User!")
MainForm.Show()
End If
Else
MsgBox("Invalid Credentials!")
End If
reader.Dispose()
End Using
End If
Catch ex As Exception
MsgBox("Try Again!")
End Try
End Sub

Add the "New" key word to your command declaration
Dim cmd As New MySqlCommand
"With" just set the properties, it does not initialize the object.

Related

Verifying StudentId and StudentPassword with mySql Database using Visual Basic

I am working on a school voting system. I Have tried this several times and there is no error but my login button doesn't work if I enter details and click login.
I use Visual Studio 2013 and would be glad if anyone can be of assistance.
Thank you
Imports MySql.Data.MySqlClient
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
ConnectToSQL()
End Sub
'connecting to sql method
Private Sub ConnectToSQL()
Dim con As New MySqlConnection
Dim cmd As New MySqlCommand
Dim StudentId As String
Dim StudentPassword As String
Try
If con.ConnectionString = "Data source= localhost; port=3306; database= Students; user=root; password=;" Then
con.Open()
cmd.Connection = con
cmd.CommandText = "SELECT StudentId, StudentPassword, StudentName FROM members"
Dim lrd As MySqlDataReader = cmd.ExecuteReader()
If lrd.HasRows Then
While lrd.Read()
StudentId = lrd("StudentId").ToString
StudentPassword = lrd("StudentPassword").ToString
If StudentPassword = TextBox1.Text And StudentId = TextBox1.Text Then
MsgBox("you logged in succesfully")
Me.Hide()
Form2.Show()
TextBox1.Text = ""
TextBox2.Text = ""
End If
End While
Else
MsgBox("Username and password do not match")
TextBox2.Text = ""
End If
End If
Catch ex As Exception
MsgBox(ex.Message)
Finally
con.Close()
End Try
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
TextBox1.Text = ""
TextBox2.Text = ""
TextBox1.Focus()
End Sub
End Class
From what I can see your problem is your first if statement:
If con.ConnectionString = "Data source= localhost; port=3306; database= Students; user=root; password=;" Then
This checks if the connectionstring is set to this value and will most definitely evaluate to false.
I assume that you want to set these settings and then open the connection to the database and not check if these settings are the set to a specific string
To make it work just remove this if statement and just set the connectionstring like this and then open the connection
con.ConnectionString = "Data source= localhost; port=3306; database= Students; user=root; password=;" Then
First, I'm going to assume you have a typo here, as it's using the username and password as the same textbox:
If StudentPassword = TextBox1.Text And StudentId = TextBox1.Text Then
Password is probably the 2nd one, forming this:
If StudentPassword = TextBox2.Text And StudentId = TextBox1.Text Then
Since you are a student and new to this, not going to get into the parameters discussion, or SQL parameters or filtering, hashing passwords or anything like that, but a couple changes:
Your else on the not hasrows:
MsgBox("Username and password do not match")
TextBox2.Text = ""
The problem with this is that in your case, having no rows just means there's no members in the database, not really information you need, or should tell someone.
Also, you don't need to blank out the username and password if you are going to hide the form anyway. The studentFound var below is used to identify if a match was found. We want to display an error if no match was found.
So, that gives us this:
While lrd.Read()
StudentId = lrd("StudentId").ToString
StudentPassword = lrd("StudentPassword").ToString
If StudentPassword = TextBox2.Text And StudentId = TextBox1.Text Then
MsgBox("you logged in succesfully")
Me.Hide()
Form2.Show()
studentFound = True
End If
End While
If Not studentFound Then
MsgBox("Username/Password Combination Not Found")
TextBox1.Text = ""
TextBox2.Text = ""
End If

MySQL login works for me but not my friend using VB

I have a program that takes info from the user and logs them into a database using Phpmyadmin, our code is the exact same, except for my friend he can't login.
Code is here:
Both our database name, tables and columns are the EXACT same, he can register the account to the DB so it stores it, but when he tries to login with the same information it says that it was unsuccessful.
SignUpForm(THIS WORKS)
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()
HashedPass = 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
LOGIN FORM(THIS DOES NOT WORK FOR HIM BUT IT WORKS FOR ME)
Imports MySql.Data.MySqlClient
Imports System.Security.Cryptography
Public Class frmLogin
Private Sub btnLogin_Click(sender As Object, e As EventArgs) Handles btnLogin.Click
Dim conStr = "Server=localhost;User Id=root;Password=;Database=accountinfo"
Dim SQL = "SELECT * FROM accountinfodb WHERE Usernames = #uname AND `Passwords` = #pword"
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()
HashedPass = System.Convert.ToBase64String(MD5hash.ComputeHash(System.Text.Encoding.ASCII.GetBytes(txtPasswd.Text)))
End Using
' this object will be closed and dispose # End Using
Using dbCon As New MySqlConnection(conStr)
' the command object likewise
Using cmd As New MySqlCommand(SQL, dbCon)
dbCon.Open()
cmd.Parameters.Add(New MySqlParameter("#uname", txtUsername.Text))
cmd.Parameters.Add(New MySqlParameter("#pword", HashedPass))
' create a Using scope block for the reader
Using rdr As MySqlDataReader = cmd.ExecuteReader
If rdr.HasRows Then
MessageBox.Show("Welcome, " & txtUsername.Text)
frmProduct.Show()
Else
MessageBox.Show("Oops! Login unsuccessful!(Password/Username may be wrong, or the user may not exist!")
txtUsername.Clear()
txtUsername.Focus()
txtPasswd.Clear()
End If
End Using
End Using ' close/dispose command
End Using ' close/dispose connection
End Sub
End Class
WOULD ALSO LIKE TO MENTION
I shared my files over google drive with him, so he did not copy and paste any of the code. This is the exact same files from MY computer.
Ok I found the issue, he was using an outdated version of MySQL while my version was the most up to date. I reinstalled the proper MySQL server to the newest version and it worked!

Connection must be valid and open VB.Net

I want to connect my MySQL to my VB.net.
I am only using Login Form.
I have given the code but the code gives me this error message: Connection must be valid and open
This is my code:
Imports MySql.Data.MySqlClient
Public Class Login
Dim MysqlConn As MySqlConnection
Dim Command As MySqlCommand
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
MysqlConn = New MySqlConnection
MysqlConn.ConnectionString ="server=db4free.net;port=3306;userid=exd****;password=****;database=exd****"
Dim Reader As MySqlDataReader
Try
MysqlConn.Open()
Dim Query As String
Query = "select * from member where Username='" & UsernameTxt.Text & "' and Password='" & PasswordTxt.Text & "' "
Command = New MySqlCommand
Reader = Command.ExecuteReader
Dim count As Integer
count = 0
While Reader.Read
count = count + 1
End While
If count = 1 Then
MessageBox.Show("Correct !")
ElseIf count > 1 Then
MessageBox.Show("Duplicate !")
Else
MessageBox.Show("Not Correct !")
End If
MysqlConn.Close()
Catch ex As Exception
MsgBox(ex.Message)
Finally
MysqlConn.Dispose()
End Try
End Sub
End Class
Can anyone help me to fix that? Thanks.
To associate your Query and Command with the connection you need to do this:
Command = New MySqlCommand(Query, MysqlConn)
You can then perform operations to retrieve the data you need.
At no point do you associate your MysqlConn nor Query to your Command before trying to call ExecuteReader on it. As such, it doesn't have a valid connection at that time.
Query = "select * from member where Username='" & UsernameTxt.Text & "' and Password='" & PasswordTxt.Text & "' ", nombredelaconexion

Invalid Operation Exception was unhandled - can't update 2 things at once

This form I made allows the user to change their username, password and/or security passphrase, and it connects and updates on XAMPP database. I have tried looking online, but I am very new to VB and nothing really makes sense.
The problem is I can change any one of them, but if I try change the other after I changed one I get the error:
InvalidOperationException was unhandled
Connection must be valid and open
The error comes here: reader = objcommand.ExecuteReader
This is my code:
`Imports MySql.Data
Imports MySql.Data.MySqlClient
Public Class frmAccountSettings
Private Sub frmAccountSettings_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
objconnection.Open()
objdataadapter.SelectCommand = New MySqlCommand
objdataadapter.SelectCommand.Connection = objconnection
objdataadapter.SelectCommand.CommandText = "Select * FROM Login"
End Sub
Private Sub btnBack_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBack.Click
frmMainMenu.Show()
Me.Hide()
End Sub
Private Sub btnChangeUsername_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnChangeUsername.Click
Dim password1, newusername As String
password1 = InputBox("What is the current password?")
sqlstring = "SELECT password FROM Login WHERE Password = '" &
password1 & "'"
objcommand = New MySqlCommand(sqlstring, objconnection)
reader = objcommand.ExecuteReader
If reader.Read Then
reader.Close()
newusername = InputBox("Enter a new username")
sqlstring = "UPDATE `Login` SET `username` = '" & newusername &
"' WHERE `Login`.`password` = '" & password1 & "'"
objdataadapter.SelectCommand.CommandText = sqlstring
objdataadapter.SelectCommand.CommandType = CommandType.Text
objdataset = New DataSet
objdataadapter.Fill(objdataset, "Login")
objconnection.Close()
Else
MsgBox("Incorrect Username. Please make sure your credentials are correct and try again.", MsgBoxStyle.Critical, "Authentication Failed")
reader.Close()
End If
End Sub
Private Sub btnChangePassword_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnChangePassword.Click
Dim oldpassword, newpassword1 As String
oldpassword = InputBox("What is the current password?")
sqlstring = "SELECT password FROM Login WHERE Password = '" &
oldpassword & "'"
objcommand = New MySqlCommand(sqlstring, objconnection)
reader = objcommand.ExecuteReader
If reader.Read Then
reader.Close()
newpassword1 = InputBox("Enter a new password")
sqlstring = "UPDATE `Login` SET `password` = '" & newpassword1 &
"' WHERE `Login`.`password` = '" & oldpassword & "'"
objdataadapter.SelectCommand.CommandText = sqlstring
objdataadapter.SelectCommand.CommandType = CommandType.Text
objdataset = New DataSet
objdataadapter.Fill(objdataset, "Login")
objconnection.Close()
Else
MsgBox("Incorrect Password. Please make sure your credentials are correct and try again.", MsgBoxStyle.Critical, "Authentication Failed")
reader.Close()
End If
End Sub
Private Sub btnChangeSecurity_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnChangeSecurity.Click
Dim password2, newsecurity As String
password2 = InputBox("What is the current password?")
sqlstring = "SELECT password FROM Login WHERE Password = '" &
password2 & "'"
objcommand = New MySqlCommand(sqlstring, objconnection)
reader = objcommand.ExecuteReader
If reader.Read Then
reader.Close()
newsecurity = InputBox("Enter a new security passphrase")
sqlstring = "UPDATE `Login` SET `security` = '" & newsecurity &
"' WHERE `Login`.`password` = '" & password2 & "'"
objdataadapter.SelectCommand.CommandText = sqlstring
objdataadapter.SelectCommand.CommandType = CommandType.Text
objdataset = New DataSet
objdataadapter.Fill(objdataset, "Login")
objconnection.Close()
Else
MsgBox("Incorrect Password. Please make sure your credentials are correct and try again.", MsgBoxStyle.Critical, "Authentication Failed")
reader.Close()
End If
End Sub
End Class
`
I think that there are a couple of errors in your code. The most serious one is a logic flaw.
You can't be sure that two users choose always different passwords. You need to make sure that your datatable Login has a primary key on the username field and use that field in your queries to uniquely identify the records to be changed. Also, changing a username used as primary key is not an easy task. You need to check if the new user name is not already taken by another user. And if your application is used in a shared environment you need to account also for concurrent changes (two user that decide to change their username to the same new name)
Also, the SelectCommand of the adapter is not the appropriate method to execute database updates. But, there is no need at all to involve the adapter for these operations, you could do everything with a MySqlCommand.
There is another security problem with storing passwords in clear text in a datatable. You should never do that, instead you should apply a hashing function to your password before storing it in the table.
However, limiting my answer to the current problem and excluding the concurrency issue, I would change your code in this way (of course username should be the primary key) ....
Dim password1, newusername, oldusername As String
oldusername = InputBox("Type the current username")
password1 = InputBox("What is the current password?")
newusername = InputBox("Enter a new username")
' identify the current user ... '
sqlstring = "SELECT COUNT(*) FROM `Login` WHERE `username` = #uname AND `password` = #pwd"
objcommand = New MySqlCommand(sqlstring, objconnection)
objcommand.Parameters.AddWithValue("#uname", oldusername)
objcommand.Parameters.AddWithValue("#pwd", password1)
Dim result = objcommand.ExecuteScalar
if result IsNot Nothing AndAlso Convert.ToInt32(result) > 0 Then
' we have good credentials, but the new user name should be unique '
sqlstring = "SELECT COUNT(*) FROM `Login` WHERE `username` = #uname"
objcommand = New MySqlCommand(sqlstring, objconnection)
objcommand.Parameters.AddWithValue("#uname", newusername)
Dim result = objcommand.ExecuteScalar
if result Is Nothing OrElse Convert.ToInt32(result) = 0 Then
' we could change the username of the current user '
sqlstring = "UPDATE `Login` SET `username` = #newame WHERE `username` = #oldname"
objcommand = New MySqlCommand(sqlstring, objconnection)
objcommand.Parameters.AddWithValue("#newame", newusername)
objcommand.Parameters.AddWithValue("#oldname", oldusername)
objcommand.ExecuteNonQuery()
else
MessageBox.Show("Username already taken, choose a different one")
End If
Else
MessageBox.Show("Invalid credentials given")
End If
In this way you use the combination of user and password to uniquely identify your user in the database and change the exact record involved.
In the same way you ask for the username and password when you want to change the password field and update the field only if the username and password match.
EDIT According to your comment above, if there is only one user in the database then you could execute directly the change without any complex checking. (But this is really a case that could not be assumed to be generally common)
sqlstring = "UPDATE `Login` SET `username` = #newame WHERE `password` = #pwd"
objcommand = New MySqlCommand(sqlstring, objconnection)
objcommand.Parameters.AddWithValue("#newame", newusername)
objcommand.Parameters.AddWithValue("#pwd", password1)
objcommand.ExecuteNonQuery()
Another problem is the connection object. It is a global object opened at the Form_Load event and then is kept hanging around your code but in some places you close it and when you try to execute another database operation you forget to reopen in. It is a good practice to NOT have a global object for the connection, instead build one when required, use it and then destroy it
For example
Private Sub btnChangeSecurity_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnChangeSecurity.Click
Using objconnection = new MySqlConnection(....connectionstring goes here ....)
objconnection.Open()
Dim sqlstring = "UPDATE `Login` SET `username` = #newame WHERE `password` = #pwd"
objcommand = New MySqlCommand(sqlstring, objconnection)
objcommand.Parameters.AddWithValue("#newame", newusername)
objcommand.Parameters.AddWithValue("#pwd", password1)
objcommand.ExecuteNonQuery()
End Using
End Sub
If you put your database access code inside a using statement like above, you create the connection object, open it, use it and when done, the End Using statement will close and destroy the connection.

MySqlDataReader giving error at build

I have a function in VB.NET that authenticates a user towards a MySQL database before launching the main application. Here's the code of the function:
Public Function authConnect() As Boolean
Dim dbserver As String
Dim dbuser As String
Dim dbpass As String
dbserver = My.Settings.dbserver.ToString
dbuser = My.Settings.dbuser.ToString
dbpass = My.Settings.dbpass.ToString
conn = New MySqlConnection
myConnString = "server=" & dbserver & ";" & "user id=" & dbuser & ";" & "password=" & dbpass & ";" & "database=rtadmin"
Dim myCommand As New MySqlCommand
Dim myAdapter As New MySqlDataAdapter
Dim myData As New DataTable
Dim myDataReader As New MySqlDataReader
Dim query As String
myCommand.Parameters.Add(New MySqlParameter("?Username", login_usr_txt.Text))
myCommand.Parameters.Add(New MySqlParameter("?Password", login_pass_txt.Text))
query = "select * from users where user = ?Username and passwd = ?Password"
conn.ConnectionString = myConnString
Try
conn.Open()
Try
myCommand.Connection = conn
myCommand.CommandText = query
myAdapter.SelectCommand = myCommand
myDataReader = myCommand.ExecuteReader
If myDataReader.HasRows() Then
MessageBox.Show("You've been logged in.", "RT Live! Information", MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
Catch ex As Exception
End Try
Catch ex As Exception
End Try
End Function
The function is not yet complete, there are a few other things that need to be done before launching the application, since I'm using a MessageBox to display the result of the login attempt.
The error that I'm getting is the following:
Error 1 'MySql.Data.MySqlClient.MySqlDataReader.Friend Sub New(cmd As MySql.Data.MySqlClient.MySqlCommand, statement As MySql.Data.MySqlClient.PreparableStatement, behavior As System.Data.CommandBehavior)' is not accessible in this context because it is 'Friend'. C:\Users\Mario\documents\visual studio 2010\Projects\Remote Techs Live!\Remote Techs Live!\Login.vb 43 13 Remote Techs Live!
Any ideas?
It makes no sense to try to create a MySqlDataReader and then throw it away!
First you do this to attempt to create a reader:
Dim myDataReader As New MySqlDataReader
Then later you attempt to throw that away when you do this:
myDataReader = myCommand.ExecuteReader
Just remove the New from your initial declaration. I suspect that the constructor for the MySqlDataReader is not publicly accessible.
You could try the .AddWithValue instead of .Add.
For example:
cmd.Parameters.AddWithValue("?Username", login_usr_txt.Text)