Syntax Error when Using Database Info in Visual Studio - vb.net

I've been trying to implement a login page where a user enters their username and password and the entered username and password are compared with those in a data table. If the username and password match a message appears saying it was successful.
I've been trying to run the code, but I keep getting a syntax error. I get the following message in visual studio:
An unhandled exception of type System.Data.OleDb.OleDbException occurred in System.Data.dll
Additional information: Syntax error (missing operator) in query expression 'User ID = 'jtenori1' AND [Password] = '''.
Code is included... Please let me know if you need more info and I appreciate the help in advance!
Private Sub btnLogin_Click(sender As Object, e As EventArgs) Handles btnLogin.Click
Dim LoginID, Password As String
LoginID = txtLoginID.Text
Password = txtPassword.Text
Dim con As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\person\Desktop\experiment\class\Project\Project41\Project41\project41.accdb")
con.Open()
Dim cmd As OleDbCommand = New OleDbCommand("SELECT * FROM UserInfo WHERE User ID = '" & txtLoginID.Text & "' AND [Password] = '" & txtPassword.Text & "' ", con)
Dim sdr As OleDbDataReader = cmd.ExecuteReader()
If (sdr.Read() = True) Then
MessageBox.Show("Successfully Logged In")
txtLoginID.Enabled = False
txtPassword.Enabled = False
Else
txtLoginID.Text = ""
txtPassword.Text = ""
MessageBox.Show("Invalid User ID or Password")
End If
End Sub

If you have User ID column then you must enclose it in [User ID].
Dim cmd As OleDbCommand = New OleDbCommand("SELECT * FROM UserInfo
WHERE [User ID] = '" & txtLoginID.Text & "' AND [Password] = '" & txtPassword.Text & "' ", con)
OR
Cross check column name used in the query with reference to name in database.
NOTE: It is highly recommended to use parameterized query.

Related

Login Process Issues

Public Class login
Dim conn As MySqlConnection
Dim Reader As MySqlDataReader
Dim cmd As MySqlCommand
Dim audit As String
Dim faudit As String
Dim connectiontime, active As String
Dim attempts As String
Dim server As String = "server=127.0.0.1;user=root;database=spilibrary"
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btnLogin.Click
Dim statement As String
Dim Userrole As String
conn = New MySqlConnection
conn.ConnectionString = server
conn.Open()
statement = "select * from user where Username = '" & username.Text & "' and Password = BINARY '" & password.Text & "'"
cmd = New MySqlCommand(statement, conn)
Reader = cmd.ExecuteReader
Try
Dim found As Boolean
While Reader.Read
found = True
Userrole = Reader.GetString("Userrole")
connectiontime = Reader.GetString("connectiontime")
attempts = Reader.GetString("attempts")
If Userrole = "Administrator" And connectiontime = "Now" Or connectiontime <= TimeOfDay.ToString("HH:mm") Then
MsgBox("Welcome Admin", MsgBoxStyle.Information, "System message")
mainform.Show()
mainform.Maintenancebtn.Enabled = True
mainform.level1.Text = Userrole
'Me.Close()
Reader.Close()
cmd = New MySqlCommand("update user set attempts = '" & "0" & "', connectiontime='" & "Now" & "' where Username='" & username.Text & "'", conn)
Reader = cmd.ExecuteReader
ElseIf Userrole = "Librarian" And connectiontime = "Now" Or connectiontime <= TimeOfDay.ToString("HH:mm:ss") Then
MsgBox("Welcome Librarian", MsgBoxStyle.Information, "System Message")
'mainform.Maintenancebtn.Enabled = False
mainform.Show()
mainform.level1.Text = Userrole
' Me.Close()
'OPAC.show()
Reader.Close()
cmd = New MySqlCommand("update user set attempts ='" & "0" & "', connectiontime ='" & "Now" & "' where Username='" & username.Text & "'", conn)
Reader = cmd.ExecuteReader
ElseIf Userrole = "Administrator" And connectiontime <> "Now" And connectiontime >= TimeOfDay.ToString("HH:mm:ss") Then
MsgBox("You're Account has been blocked because of multiple failed attempts", vbCritical, "System Message")
ElseIf Userrole = "Librarian" And connectiontime <> "Now" And connectiontime >= TimeOfDay.ToString("HH:mm:ss") Then
MsgBox("Your Account has been blocked because of multiple failed attempts", vbCritical, "System Message")
Else
MsgBox("You're Account whas been blocked because of multiple failed attempts", vbCritical, "System Message")
End If
Someone please help me with this.. when i hit login button it always reads the first if-else statement i enter which is the Userrole="administrator" even if im logging in my Librarian Userrole. when i try to switch them the It reads the librarian userrole and not the admin even if im logging my admin userrole.. in my database they are declared right. so maybe it's the code. Thank you
Try using brackets in your condition to make it clearer. Like this:
If Userrole = "Administrator" AndAlso (connectiontime = "Now" OrElse connectiontime <= TimeOfDay.ToString("HH:mm")) Then
in your code, it would also match if
connectiontime <= TimeOfDay.ToString("HH:mm")

"An unhandled exception of type 'System.InvalidOperationException' occurred in System.Data.dll" visual studio vb.net using database microsoft access

im a beginner in vb.net and when i start my coding the error "An unhandled exception of type 'System.InvalidOperationException' occurred in System.Data.dll" i dont know what to do. this is my code.
Dim cmd As New OleDbCommand("SELECT * FROM [login] WHERE [ID] & [Password] =" & TextBoxUsername.Text & TextBoxPassword.Text & "", myConnection)
myConnection.Open() '*its keep pointing at this*
Dim dr As OleDbDataReader = cmd.ExecuteReader
Dim userFound As Boolean
Dim userID As String = ""
Dim UserPassword As String = ""
While dr.Read
userFound = True
userID = dr("ID").ToString
UserPassword = dr("Password").ToString
Form2.Show()
Me.Hide()
End While
If userFound = False Then
MessageBox.Show("Invalid Username/Password")
'Button","User Validation", MessageBoxButton.OK , MessageBoxIcon.Error)'
End If
myConnection.Close()
End Sub
End Class**
You aren't currently wrapping your parameters in single quotes and your WHERE clause syntax appears to be off. It's likely you want something like this :
"SELECT * FROM [login] WHERE [ID] = '" & TextBoxUsername.Text & "' AND [Password] = '" & TextBoxPassword.Text & "'"
A larger issue here is that you should be using parameters to build your query, which can not only help you avoid issues like this, but it can also help prevent nasty things like SQL Injection :
' Build your connection '
Using(Dim myConnection As New OleDbConnection("{your-connection-string"}))
' Use parameters in your query '
Dim query = "SELECT * FROM [login] WHERE [ID] = ? AND Password = ?"
' Build your command to execute '
Using(Dim myCommand As New OleDbCommand(query, myConnection))
' Open your connection '
myConnection.Open()
' Add your parameters (these will replace the ? in your query)
myCommand.Parameters.AddWithValue("#ID",TextBoxUsername.Text)
myCommand.Parameters.AddWithValue("#Password",TextBoxPassword.Text)
Using(Dim myReader = myCommand.ExecuteReader())
If myReader.HasRows Then
' Do stuff '
userFound = True
userID = dr("ID").ToString
UserPassword = dr("Password").ToString
Form2.Show()
Me.Hide()
Else
' Do other stuff '
MessageBox.Show("Invalid Username/Password")
End If
End Using
End Using
End Using

syntax error (missing operator) two user in login form

Syntax error (missing operator) in query expression 'Username ='admin' [Password] ='admin' AND AccountType = Admin''.
Dim conn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Jen\Documents\Jade\vb\database.accdb")
txtAdmin.Text = "Admin"
Dim strsql As New OleDbCommand("select * from Login where Username ='" & txtUsername.Text & "' [Password] ='" & txtPassword.Text & "' AND AccountType = Admin'", conn)
Dim uu As New OleDbParameter("UserName", txtUsername.Text)
Dim pp As New OleDbParameter("Password", txtPassword.Text)
strsql.Connection.Open()
Dim reader As OleDbDataReader
reader = strsql.ExecuteReader
If reader.HasRows Then
strsql.Connection.Close()
MsgBox(" Successfully Logged in!", vbInformation)
frmIndex.Show()
desktopFade.Close()
ElseIf txtUsername.Text = "" And txtPassword.Text = "" Then
MsgBox("Don't leave the fields blank", vbCritical)
txtUsername.Focus()
Else
MsgBox("Your Username or Password is invalid", MsgBoxStyle.Critical)
Me.txtUsername.Text = ""
Me.txtPassword.Text = ""
Me.txtUsername.Focus()
strsql.Connection.Close()
End If
i have 2 user in the database. the admin and the user. if the username and password account type is = Admin then ADMIN Account show while if the username and password input is for the user then USER Account show. On my code, i'm trying to solve first the admin but i need everyone help. T.T
You miss an "AND" here:
'" & txtUsername.Text & "' [Password] ='"
Should be
'" & txtUsername.Text & " AND ' [Password] ='"

Selecting radiobuttons from database?

I would like my database to also select radiobuttons from my access database. However whenever I try running my program and providing the needed information, an error shows up
" Error:Syntax error in string in query expression 'username=asjjm'
AND password = 'ksjadklf' AND facultymember = 'False' AND student =
'False. "
I don't really understand errors like that because I'm only a beginner. Can someone tell me whats wrong? Thank you very much.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLogin.Click
' Check if username or password is empty
If TxtPassword.Text = "" Or TxtUsername.Text = "" Then
MessageBox.Show("Please complete the required fields.", "Authentication Error!", MessageBoxButtons.OK, MessageBoxIcon.Error)
Else
' Both fields was supply
' Check if user exist in database
' Connect to DB
Dim conn As New System.Data.OleDb.OleDbConnection()
conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Thesis\Thesis\Database2.accdb"
Try
'conn.Open()
'MsgBox("Susscess")
Dim sql As String = "SELECT * FROM tbl_user WHERE username='" & TxtUsername.Text & "' AND password = '" & TxtPassword.Text & "' AND facultymember = '" & RadioButton1.Checked & "' AND student ='" & RadioButton2.Checked '""
Dim sqlCom As New System.Data.OleDb.OleDbCommand(sql)
'Open Database Connection
sqlCom.Connection = conn
conn.Open()
Dim sqlRead As System.Data.OleDb.OleDbDataReader = sqlCom.ExecuteReader()
If sqlRead.Read() Then
MainStud.Show()
Me.Hide()
Else
' If user enter wrong username and password combination
' Throw an error message
MessageBox.Show("Username, Password, and Account Type do not match!", "Authentication Failure", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
'Clear all fields
TxtPassword.Text = ""
TxtUsername.Text = ""
'Focus on Username field
TxtUsername.Focus()
conn.Close()
End If
Catch ex As Exception
MessageBox.Show("Error:" & ex.Message)
End Try
End If
End Sub
*Edit
I did exactly what #chepe263 said and got two new errors.
End of statement expected
'System.Data.Sql' is a namespace and cannot be used as an expression.
What's causing these? Note* I made the radiobuttons to indicate choices whether the user is logging in on an account as a faculty member or student.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLogin.Click
' Check if username or password is empty
If TxtPassword.Text = "" Or TxtUsername.Text = "" Then
MessageBox.Show("Please complete the required fields.", "Authentication Error!", MessageBoxButtons.OK, MessageBoxIcon.Error)
Else
' Both fields was supply
' Check if user exist in database
' Connect to DB
Dim conn As New System.Data.OleDb.OleDbConnection()
conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Thesis\Thesis\Database2.accdb"
Try
'conn.Open()
'MsgBox("Susscess")
Dim facultyMemberName As String
Dim rbdtext As String
If RadioButton1.Checked Then
facultyMemberName = RadioButton1.Text
End If
If RadioButton2.Checked Then
rbdtext = RadioButton2.Text
End If
Dim sql As String = "SELECT * FROM tbl_user WHERE username='" & TxtUsername.Text & "' AND password = '" & TxtPassword.Text & "' AND facultymember = '" & facultyMemberName & "' AND student ='" & rbdtext """
Dim sqlCom As New System.Data.OleDb.OleDbCommand(Sql, conn)
'Open Database Connection
sqlCom.Connection = conn
conn.Open()
Dim sqlRead As System.Data.OleDb.OleDbDataReader = sqlCom.ExecuteReader()
If sqlRead.Read() Then
MainStud.Show()
Me.Hide()
Else
' If user enter wrong username and password combination
' Throw an error message
MessageBox.Show("Username and Password do not match!", "Authentication Failure", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
'Clear all fields
TxtPassword.Text = ""
TxtUsername.Text = ""
'Focus on Username field
TxtUsername.Focus()
conn.Close()
End If
Catch ex As Exception
MessageBox.Show("Error:" & ex.Message)
End Try
End If
End Sub
Edit* Still not over this. Tried every possible solution but still shows errors. Sorry if it could get so confusing. I'm just a beginner.
you try something like this
if (RadioButton1.Checked)
{
rbdtext = RadioButton1.Text;
}
else if (RadioButton2.Checked)
{
rbdtext = RadioButton2.Text;
}
else
{
rbdtext = RadioButton3.Text;
}
then your SQL Statement
Dim sql As String = "SELECT * FROM tbl_user WHERE username='" & TxtUsername.Text & "' AND password = '" & TxtPassword.Text & "' AND facultymember = '" & rbdtext & "' AND student ='" & rbdtext '""
declare a new variable inside Button Click's Private sub
Dim facultyMemberName as String
Do what Parth Akbari suggests
If RadioButton1.Checked Then
facultyMemberName = RadioButton1.Text
End If
(Repeat for as many radio buttons you have)
Then place the right variable name and fix the end of your string (the single quote is before the double quote and it makes it a commentary, no good)
Dim sql As String = "SELECT * FROM tbl_user WHERE username='" & TxtUsername.Text & "' AND password = '" & TxtPassword.Text & "' AND facultymember = '" & facultyMemberName & "' AND student ='" & rbdtext """
Tips (just opinions)
Try using a ListBox or ComboBox instead of RadioButtons since you are listing names of people. You could do something like
facultyMemberName = lstFacultyName.SelectedItem.Text
Try placing your sql query in a textbox, copy it and run it with your favorite SQL manager. You can detect potential errors that way.
Try using parameters instead of concatenate values to a string.

Error when trying to run login form vb.net

Here's my code...
Imports System.Data
Imports System.Data.SqlClient
Public Class Form1
Dim con As SqlConnection
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
con = New SqlConnection("Server=localhost\SQLEXPRESS;Database=Vehicle;Trusted_Connection=True;")
con.Open()
Dim dr As SqlClient.SqlDataReader
Dim cmd As New SqlClient.SqlCommand("SELECT * FROM [user] where userid= " + txtuser.Text + " AND password= " + txtpass.Text + "", con)
dr = cmd.ExecuteReader
If dr.Read Then
MsgBox("Succesfully loggedin")
End If
con.Close()
End Sub
End Class
when I try to run the programs, it shows this error:
An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Additional information: Invalid column name 'admin'.
Invalid column name 'admin'.
'admin' is on the value stored in the userid column under 'user' table under 'Vehicle' database..I'm creating a small Win application for our office but I was stacked with this one, this is also part of my practice.
thanks for the help guys..
I'll start with a warning: use SQLParameter to avoid SQL injection!
In this case the problem is that you pass a SELECT like this:
SELECT * FROM [user] where userid = admin
So SQL Server thinks admin is a column name.
The correct syntax is:
SELECT * FROM [user] where userid = 'admin'
you need to escape your text. This is what your DB sees:
SELECT * FROM [user] where userid= admin AND password= somepass
This is what you want it to see:
SELECT * FROM [user] where userid= 'admin' AND password = 'somepass'
To fix this, re-write your code like:
"SELECT * FROM [user] where userid= '" + txtuser.Text + "' AND password= '" + txtpass.Text + "'"
(note the single quotes).
You should also worry about what would happen if the userid or password included a single quote, you can fix this by doing Replace(txtuser.Text,"'","''")
You need to encase the contents txtUser.Text and txtPass.Text in apostrophes, to escape them. You're currently trying to match a column called admin.
For example;
Dim cmd As New SqlClient.SqlCommand("SELECT * FROM [user] where userid='" & txtuser.Text & "' AND password='" & txtpass.Text & "';", con)
dr = cmd.ExecuteReader
What you really should be doing is something like this;
Dim cmd As New SqlClient.SqlCommand("SELECT * FROM [user] WHERE userid=#U AND password=#P;", con)
cmd.Parameters.Add("#U", SqlDBType.NVarChar).Value = txtUser.Text.Trim
cmd.Parameters.Add("#P", SqlDBType.NVarChar).Value = txtPass.Text.Trim
dr = cmd.ExecuteReader
I find this simplifies things quite a bit.