I am trying to make a query that deletes the user from my database.
But when i confirm to delete the user it gives me an error:
System.Data.SqlClient.SqlException (0x80131904): Must declare the scalar variable "#Username".
Imports System.Data.SqlClient
Public Class DeleteForm
Private Sub btnDelete_Click(sender As Object, e As EventArgs) Handles btnDelete.Click
Dim RetVal As Integer
Dim conn = New SqlConnection("Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=dbProject;Integrated Security=True")
Using cmd = New SqlCommand("select count(*) from tblLogin where username = #Username and password = #Password", conn)
cmd.Parameters.Add("#Username", SqlDbType.VarChar).Value = txtUsername.Text
cmd.Parameters.Add("#Password", SqlDbType.VarChar).Value = txtPassword.Text
conn.Open()
If conn.State = ConnectionState.Open Then
RetVal = CInt(cmd.ExecuteScalar)
If RetVal = 1 Then
If txtPassword.Text And txtCheckPassword.Text <> "" Then
If txtCheckPassword.Text = txtPassword.Text Then
Dim cancConf As Integer = MessageBox.Show("This cant be undone!" & vbCrLf & "Are you sure?", "Warning!", MessageBoxButtons.YesNo, MessageBoxIcon.Warning)
If cancConf = DialogResult.Yes Then
Try
Dim queryDelete As String = "DELETE FROM tblLogin WHERE username = #Username"
Dim cmdDelete As New SqlClient.SqlCommand(queryCancellazione, conn)
cmdCancellazione.ExecuteNonQuery()
MsgBox("Account deleted succesfully!")
cmdCancellazione.Dispose()
conn.Close()
LoginForm.Show()
Me.Close()
Catch ex As Exception
MsgBox(ex.ToString())
End Try
ElseIf cancConf = DialogResult.No Then
End If
Else
MsgBox("The passwords arent matching!", MsgBoxStyle.Exclamation)
End If
ElseIf txtPUtenteCANC.Text <> "" And txtPUtenteCONF.Text = "" Then
MsgBox("Please, confirm the password")
End If
Else
MsgBox("User not found!", MsgBoxStyle.Exclamation)
txtNUtenteCANC.Clear()
txtPUtenteCANC.Clear()
txtPUtenteCONF.Clear()
txtNUtenteCANC.Select()
End If
Else
MessageBox.Show("The connection is not open!" & vbCrLf & "The program will close", "Warning!", MessageBoxButtons.OK, MessageBoxIcon.Error)
End
End If
End Using
End Sub
End Class
You have added that parameter to the SELECT COUNT command but not to the DELETE command.
Dim queryCancellazione As String = "DELETE FROM tblLogin WHERE username = #Username"
Dim cmdCancellazione As New SqlClient.SqlCommand(queryCancellazione, conn)
cmdCancellazione.Parameters.Add("#Username", SqlDbType.VarChar).Value = txtUsername.Text
Related
I'm trying to make a login form.
I've created a database on my server and created the rows username and password.
I then created a root user with root as password.
but I have a problem with the check if the username and password are correct,
I don't know how to give him the 2 rows.
Dim conn = New SqlConnection("Data Source=SRV-SQL;Initial Catalog=prova;User ID=user;Password=user")
Dim sda = New SqlDataAdapter("select count(*) from tblLogin where username ='" + txtUsername.Text + "' and password='" + txtUserPwd.Text + "'", conn)
Dim dt = New DataTable()
sda.Fill(dt)
If (dt.Rows().ToString() = "1") Then
MsgBox("Logged-in successfully")
Else
MessageBox.Show("The username or the password is wrong!", "Warning!", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
Table:
Comments and explanations in-line.
Private Sub VerifyLogin()
'For the Return Value of the command
Dim RetVal As Integer
' A Using...End Using will ensure that you connectionis closed and disposed event
'it there is an error.
Using conn = New SqlConnection("Data Source=SRV-SQL;Initial Catalog=prova;User ID=user;Password=user")
'You don't need a DataAdapter, just a command
'USE PARAMETERS. Yes, I am yelling :-) Even if you are the only user
'it will save you headaches with syntax.
Using cmd = New SqlCommand("select count(*) from tblLogin where username = #UserName and password= #Password;", conn)
cmd.Parameters.Add("#UserName", SqlDbType.VarChar).Value = txtUsername.Text
cmd.Parameters.Add("#Password", SqlDbType.VarChar).Value = txtUserPwd.Text
'You are only returning one row
'ExecuteScalar returns the value in the first column of the
'first row of the the data
conn.Open()
RetVal = CInt(cmd.ExecuteScalar)
End Using
End Using
'No need to convert to a string just compare the Integer
If RetVal = 1 Then
MsgBox("Logged-in successfully")
Else
MessageBox.Show("The username or the password is wrong!", "Warning!", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
End Sub
Private Function CalculateHash(password As String, salt As String) As String
'TODO:
' Suggest pulling the BCrypt from the NuGet gallery for this:
' https://www.nuget.org/packages/BCrypt-Official/
' Just remember that bcyrpt lib encodes salt as part of the password hash, so the function signatures and db table will be different.
End Function
Public Function CheckCredentials(UserName As String, Password As String) As Boolean
Using conn As New SqlConnection("Data Source=SRV-SQL;Initial Catalog=prova;User ID=user;Password=user"), _
' Need to add a "Salt" column to your table, create a new random salt for each user when you create the user
cmd As New SqlCommand("SELECT Salt, PwdHash FROM tblLogin WHERE username = #Username", conn)
'Parameterized queries or NOTHING. String concatention is NOT OKAY here
cmd.Parameters.Add("#UserName", SqlDbType.NVarChar, 50).Value = UserName
conn.Open()
Using rdr As SqlDataReader = cmd.ExecuteReader()
If Not rdr.Read() Then Return False
Dim Salt As String = rdr("Salt")
Dim PwdHash As String = rdr("PwdHash")
'Compare HASHES, not Passwords
Return PwdHash = CalculateHash(Password, Salt As String)
End Using
End Using
End Function
If CheckCredentials(txtUsername.Text, txtUserPwd.Text) Then
MsgBox("Logged-in successfully")
Else
MessageBox.Show("The username or the password is wrong!", "Warning!", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
Use DataReader instead, use this code and just call CheckLogin in login button or somthing else.
Sub CheckLogin()
Dim conn = New SqlConnection("Data Source=SRV-SQL;Initial Catalog=prova;User ID=user;Password=user")
conn.Open()
Try
Dim query As String = "select count(*) from tblLogin where username = #username and password= #password "
Dim cmd = New SqlCommand(query, conn)
cmd.Parameters.AddWithValue("#username", txtUsername.Text)
cmd.Parameters.AddWithValue("#password", txtUserPwd.Text)
Dim DR As SqlDataReader = cmd.ExecuteReader()
If DR.HasRows Then
MsgBox("Logged-in successfully")
Else
MessageBox.Show("The username or the password is wrong!", "Warning!", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
conn.Close()
End Sub
I'm creating a login register with edit information. I'm stuck with the change password form.
Here's what I got - totally lost it, no errors but crashes when tested highlights my reader command
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
Dim sql As String = "Select Username, Password From tblLog Where Username = #Username"
Dim cmd As SqlClient.SqlCommand
cmd = New SqlClient.SqlCommand(sql, con)
cmd.Parameters.Add("#Username", SqlDbType.VarChar).Value = My.Forms.formEdit.tbUser.Text
If con.State = ConnectionState.Closed Then
con.Open()
End If
Dim rd As SqlClient.SqlDataReader = cmd.ExecuteReader
Try
If rd.Read = False Then
MessageBox.Show("Incorrect Password")
tbOldPass.Clear()
tbNewPass.Clear()
tbConPass.Clear()
ElseIf tbConPass.Text <> tbNewPass.Text Then
MessageBox.Show("Password does not match")
tbOldPass.Clear()
tbNewPass.Clear()
tbConPass.Clear()
Else
Dim sqry As String = "Update tblLog Set Password = #Password" &
"Where Username = #Username And Password = #OldPassword"
rd.Close()
Dim scmd As New SqlClient.SqlCommand(sqry, con)
scmd.Parameters.AddWithValue("#Password", tbNewPass.Text)
scmd.Parameters.AddWithValue("#Username", My.Forms.formEdit.tbUser.Text)
scmd.Parameters.AddWithValue("#OldPassword", tbOldPass.Text)
scmd.ExecuteNonQuery()
MessageBox.Show("Information Updated")
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
con.Close()
End Sub
Edited: Changed the code a bit, it doesn't crash anymore but my database doesn't get updated
Dim sql As String = "Select Username, Password From tblLog Where Username = #Username And Password = #Password"
Dim cmd As New SqlClient.SqlCommand
cmd = New SqlClient.SqlCommand(sql, con)
cmd.Parameters.Add("#Password", SqlDbType.VarChar).Value = My.Forms.formEdit.tbPass.Text
cmd.Parameters.Add("#Username", SqlDbType.VarChar).Value = My.Forms.formEdit.tbUser.Text
If con.State = ConnectionState.Closed Then
con.Open()
End If
cmd.ExecuteNonQuery()
con.Close()
Try
If tbOldPass.Text <> My.Forms.formEdit.tbPass.Text = False Then
MessageBox.Show("Incorrect Password")
tbOldPass.Clear()
tbNewPass.Clear()
tbConPass.Clear()
ElseIf tbConPass.Text <> tbNewPass.Text Then
MessageBox.Show("Password does not match")
tbOldPass.Clear()
tbNewPass.Clear()
tbConPass.Clear()
Else
Dim sqry As String = "Update tblLog Set [Password] = #Pss Where Username = #Use And Password = #OldPassword"
Dim scmd As New SqlClient.SqlCommand(sqry, con)
scmd.Parameters.AddWithValue("#Pss", tbNewPass.Text)
scmd.Parameters.AddWithValue("#Use", My.Forms.formEdit.tbUser.Text)
scmd.Parameters.AddWithValue("#OldPassword", My.Forms.formEdit.tbPass.Text)
If con.State = ConnectionState.Closed Then
con.Open()
End If
scmd.ExecuteNonQuery()
con.Close()
MessageBox.Show("Information Updated")
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
Try Adding space before where in query:
Dim sqry As String = "Update tblLog Set Password = #Password" &
" Where Username = #Username And Password = #OldPassword"
After tweaking my code a bit I realized that I was closing the form where the value of my parameters were taken. So I tried to just hide the form not close it, then it worked. Sorry for the troubles.
Edit:
Should I delete this question or just leave it? I can't select my own answer as the correct for 2 more days
Hello guys am having issues with my login form for multiple users of my software, below is the complete login button code for the admin
Private Sub btnlogin_Click(sender As System.Object, e As System.EventArgs) Handles btnlogin.Click
If cmbusertype.Text = "" Then
MsgBox("Please select the appropriate Account Type!", vbExclamation, "Account Type")
End If
If cmbusertype.Text = "Admin" Then
Dim Strconn As String = "Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\phermacy.mdf;Integrated Security=True;User Instance=True"
Dim Selectcmd As String = "select * from tbl_admin where admin_username = '" + txtusername.Text + "' and password = '" + txtpassword.Text + "'"
Dim da As New SqlDataAdapter
Dim ds As New DataSet
Dim sqlcmd As SqlCommand
sqlconn = New SqlConnection(Strconn)
Try
sqlconn.Open()
Catch ex As Exception
MsgBox("Could not connect to DataBase. Application will close now!", vbCritical, "Database Error")
End
End Try
sqlcmd = New SqlCommand(Selectcmd, sqlconn)
da.SelectCommand = sqlcmd
sqlcmd.Dispose()
sqlconn.Close()
da.Fill(ds)
Matching Admin User Name & Password
If ds.Tables(0).Rows.Count > 0 Then
If txtusername.Text = ds.Tables(0).Rows(0).Item(0) And txtpassword.Text = ds.Tables(0).Rows(0).Item(1) Then
MsgBox("Administrator Log-in Successful.", vbInformation, "Admin Log-in")
Me.Hide()
adminform.Show()
Else
ErrorProvider1.SetError(txtusername, "Invalid User Name.")
ErrorProvider1.SetError(txtpassword, "Invalid Password.")
MsgBox("Invalid Administrator Username or Password.", vbCritical, "Admin Log-in")
End If
Else
ErrorProvider1.SetError(txtusername, "Invalid User name or Password.")
ErrorProvider1.SetError(txtpassword, "Invalid User name or Password.")
ErrorProvider1.SetError(cmbusertype, "Please select the appropriate Account Type")
MsgBox("Invalid Administrator Username or Password.", vbCritical, "Admin Log-in")
End If
End If
End Sub
the code line highlighted is the following
If txtusername.Text = ds.Tables(0).Rows(0).Item(0) And txtpassword.Text = ds.Tables(0).Rows(0).Item(1) Then
and the error is "Conversion from string "admin" to type 'Double' is not valid." am actually new to vb trying to create a login for multiple users, the above part as you can see is just for the admin. Please any help here will be appreciated thanks.
Try this...
Private Sub btnlogin_Click(sender As System.Object, e As System.EventArgs) Handles btnlogin.Click
If cmbusertype.Text = "" Then
MsgBox("Please select the appropriate Account Type!", vbExclamation, "Account Type")
End If
If cmbusertype.Text = "Admin" Then
Dim Strconn As String = "Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\phermacy.mdf;Integrated Security=True;User Instance=True"
Dim Selectcmd As String = "select * from tbl_admin where admin_username = #usernme and password = #paswd"
Dim da As New SqlDataAdapter
Dim ds As New DataSet
Dim sqlcmd As SqlCommand
sqlconn = New SqlConnection(Strconn)
Try
sqlconn.Open()
Catch ex As Exception
MsgBox("Could not connect to DataBase. Application will close now!", vbCritical, "Database Error")
End
End Try
sqlcmd = New SqlCommand(Selectcmd, sqlconn)
sqlcmd.parameters.addwithValue("#usernme",txtusername.Text)
sqlcmd.parameters.addwithValue("#paswd",txtpassword.Text)
da.SelectCommand = sqlcmd
sqlcmd.Dispose()
sqlconn.Close()
da.Fill(ds)
Okay I have created a log in system on VB.net using a database on access. The problem I am having is that some of the username and password combinations work perfectly, but some of them, although put in correctly, don't work at all. This is the code I have written...
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
' Check if username or password is empty
If textpassword.Text = "" Or textusername.Text = "" Then
MessageBox.Show("Please complete the required fields..", "Authentication Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Else
' Both fields were supplied
' 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=|DataDirectory|\database1.accdb"
'conn.Open()
'MsgBox("Susscess")
Dim sql As String = "SELECT * FROM Accounts WHERE username='" & textusername.Text & "' AND password = '" & textpassword.Text & "'"
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
MemberPage.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
textpassword.Text = ""
textusername.Text = ""
'Focus on Username field
textusername.Focus()
End If
End If
End Sub
Do not Concatenate string.Its wide open for SQL injection .Its better to use Parameterized query
Dim sql As String = "SELECT * FROM Accounts WHERE username=? AND password = ?"
Dim sqlCom As New System.Data.OleDb.OleDbCommand(sql)
sqlCom.Parameters.AddWithValue("?", textusername.Text);
sqlCom.Parameters.AddWithValue("?", textpassword.Text);
Also you can use HasRows property
If sqlRead.HasRows Then
While sqlRead.Read()
MemberPage.Show()
Me.Hide()
End While
Else
MessageBox.Show("Username and Password do not match..", "Authentication Failure", MessageBoxButtons.OK, MessageBoxIcon.Exclamation) 'Clear all fields
textpassword.Text = ""
textusername.Text = ""
'Focus on Username field
textusername.Focus()
End If
It seems that some mistake is happening at the condition you checking after filling the dataReader. i.e
If sqlRead.Read() Then
try the if condition by following code
If Not sqlRead Is Nothing Then
if it doesnt work then..
I would suggest you to do it using DataAdapter and check whether it returns rows. if the row count is greater than 1 , you must show the MemberPage
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If textpassword.Text = "" Or textusername.Text = "" Then
MessageBox.Show("Please complete the required fields..", "Authentication Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Else
Dim conn As New System.Data.OleDb.OleDbConnection()
conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\database1.accdb"
Dim sql As String = "SELECT * FROM Accounts WHERE username='" & textusername.Text & "' AND password = '" & textpassword.Text & "'"
Dim sqlCom As New System.Data.OleDb.OleDbCommand(sql)
Dim ds As DataSet
sqlCom.Connection = conn
conn.Open()
'Dim sqlRead As System.Data.OleDb.OleDbDataReader = sqlCom.ExecuteReader()
Dim da as New OleDbDataAdapter(sqlCom)
da.Fill(ds)
If ds.Tables(0).Rows.Count > 1 Then
MemberPage.Show()
Me.Hide()
Else
MessageBox.Show("Username and Password do not match..", "Authentication Failure", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
textpassword.Text = ""
textusername.Text = ""
textusername.Focus()
End If
End If
End Sub
I am getting an exception when I run the below VB.NET code to validate a user..The exception says that "Incorrect syntax near variable user"
Can anyone tell me where am I going wrong ?
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If TextBox1.Text.Trim().Length = 0 Or TextBox2.Text.Trim().Length = 0 Then
MsgBox("Enter a user id and password")
Return 'Terminate this method
End If
Dim myconnection As SqlConnection
Dim mycommand As SqlCommand
Dim dr As SqlDataReader
Dim userid = TextBox1.Text
Dim password = TextBox2.Text
Try
myconnection = New SqlConnection("server=PARTH- PC\SQLEXPRESS;uid=sa;pwd=parth;database=fcrit")
myconnection.Open()
mycommand = New SqlCommand("select * from user where [user id]=#userid and [password]=#password", myconnection)
mycommand.Parameters.Add("#userid", SqlDbType.VarChar, 30).Value = userid
mycommand.Parameters.Add("#password", SqlDbType.VarChar, 30).Value = password
'mycommand = New SqlCommand("select * from user where user id='" & TextBox1.Text & "' and password='" & TextBox2.Text & "'", myconnection)
dr = mycommand.ExecuteReader()
If (dr IsNot Nothing) Then
If (dr.Read()) Then
MsgBox("User is authenticated")
Form2.Show()
Else
MsgBox("Please enter correct username and password")
End If
End If
myconnection.Close()
Catch ex As Exception
Throw
Finally
End Try
End Sub
Try changing your SQL to -
"select * from [user] where [user id]=#userid and [password]=#password"
According to this page 'User' is a reserved word
User is a reserved word in SQL Server.
Put brackets around the table name:
mycommand = New SqlCommand("select * from [user] where [user id]=#userid and [password]=#password", myconnection)