There are a few problems with your code
SELECT Username, Password
FROM Users
WHERE Username = txtUserid
AND Password = txtPassword
1. Why are you selecting the username and password when you already know them?
2. This query compares the un/pw to other columns, and not to user input.
3. It would be recommended to hash or encrypt the password, this looks like plain-text
I would change the query up to just get the
Count
, and use the parameters.
SELECT Count(*)
FROM Users
WHERE Username = @Username
AND Password = @Password
The next few lines look OK, you add in the parameters
(which don't exist in the query but we're adding it in) and we get to the execution.
1. Set Login = 0
2. If there are rows, set Login to be the reader
3. Compare the Login value to
nothing to see if the login failed
Umm... The login will be
0
if there were no rows found, not
nothing.
Regardless, we already need to change this to reflect the altered SQL (Count) statement anyways.
So at this point I am rewriting your code to adapt it to new logic, and to simplify the parameters.. and I think I found your problem... you never set the Connection
property of the SqlCommand
Try
Dim myQuery as String = "SELECT Count(*) FROM Users WHERE Username=@Username and Password=@Password"
Dim myConnection As OleDb.OleDbConnection
myConnection = New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + "D:\myvbsbs\NES\NES\Database1.accdb")
Dim myCommand As OleDbCommand = New OleDbCommand(myQuery, myConnection)
myCommand.Parameters.AddWithValue("@Username", txtUserid.Text)
myCommand.Parameters.Add("@Password", txtPassword.Text)
myCommand.Connection.Open()
Dim Login As Int32 = myCommand.ExecuteScalar()
If Login = 0 Then
MsgBox("Login Failes !!!!", MsgBoxStyle.Critical, "Error.")
txtUserid.Clear()
txtPassword.Clear()
txtUserid.Focus()
Else
ProgressBar1.Visible = True
ProgressBar1.Maximum = 5000
ProgressBar1.Minimum = 0
ProgressBar1.Value = 4
ProgressBar1.Step = 1
For i = 0 To 5000
ProgressBar1.PerformStep()
Next
FrmMain.ToolStripStatusLabel2.Text = txtUserid.Text
Me.Hide()
FrmMain.Show()
End If
myCommand.Dispose()
myConnection.Close()
Catch ex As Exception
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
Notes and recommendations:
1. VB is not my native language, and this was done in Notepad. There may be typos.
2. Many of the Sql objects have overloaded methods which were used, fewer lines.
3. As noted the passwords should not be plain-text; see the link from
@OriginalGriff
4. As
@Patrice T
noted, you may want to comment out the try...catch for testing