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)
Related
I've been trying to insert data into my sql database but this problem always show up
i've tried redoing it again and the same problem occurs and i'm really stumped right now
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim conn As SqlConnection = New SqlConnection("Data Source=DESKTOP-OBQR58O\SQLEXPRESS;Initial Catalog=Accounts;Integrated Security=True")
Dim comm As SqlCommand = New SqlCommand("insert into User(username, password)values('" + TextBox1.Text + "', '" + TextBox3.Text + "')", conn)
Dim data As SqlDataAdapter = New SqlDataAdapter(comm)
Dim user = TextBox1.Text
Dim pass = TextBox2.Text
Dim cpass = TextBox3.Text
Dim reader As SqlDataReader
conn.Open()
Dim cmd As SqlCommand = New SqlCommand("select Username from [User] where Username ='" + TextBox1.Text + "'", conn)
conn.Close()
conn.Open()
reader = cmd.ExecuteReader
If user.Trim() = "" Or pass.Trim() = "" Or cpass.Trim() = "" Then
MessageBox.Show("Empty Fields", "Blank Spaces")
ElseIf Not String.Equals(pass, cpass) Then
MessageBox.Show("Passwords do not match", "ERROR")
conn.Close()
ElseIf reader.HasRows Then
MessageBox.Show("Username already exists!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning)
TextBox1.Clear()
conn.Close()
reader.Close()
Else
MessageBox.Show("Account created succesfully!", "Success")
Dim table As DataTable = New DataTable()
data.Fill(table) ' this is where the problem occurs.
TextBox1.Clear()
TextBox2.Clear()
TextBox3.Clear()
Dim log As New Login
Me.Close()
log.Show()
conn.Close()
End If
conn.Close()
End Sub
I honestly don't know what to do
You open your reader up at the top:
reader = cmd.ExecuteReader
So, it's open. And then, when you run the Fill command, it conflicts with the open reader!
The simplest fix - although, personally, I would restructure the code a bit, to bring the OpenReader nearer to where it is used - would be to add a Close to your reader right before the Fill.
Else
reader.Close() ' what you would add
MessageBox.Show("Account created succesfully!", "Success")
Dim table As DataTable = New DataTable()
data.Fill(table) ' this is where the problem occurs.
VERY IMPORTANT: If you're not familiar with the concept of "SQL Injection Attacks", read up on them, right away. You should NEVER execute SQL that's been built by constructing a string with unvalidated data from the user. You should pass parameters instead.
After all, what if I typed in the user name of "Irrelevant';DROP TABLE Users;--"? You'd wind up with a SQL Statement that contained "SELECT Username from [Users] WHERE [Username] = 'Irrelevant'; DROP TABLE Users; --'"
And, of course, you should validate the input as well, for things like embedded HTML and script! But that's more complicated than just using SQL Parameters.
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
I'm trying to search a keyword in the SQL Server db from Textbox1 and printing the corresponding details in other TextBoxes.
While running the below code, it shows it is unable to convert the DateTime and Integer value into String to display it in the TextBoxes.
Also there is another end of statement expected error in the command.Parameter line:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim connection As New SqlConnection("Server= DESKTOP-STMQUHM; Database = HospitalDB;Trusted_Connection=True")
Dim command As New SqlCommand("select * from Medicines where MedicineName ='" & TextBox1.Text & "' ", connection)
command.Parameters.Add("#Textbox1",SqlDbType.Text)Value=TextBox1.Text 'Another error
Dim adapter As New SqlDataAdapter(command)
Dim table As New DataTable()
adapter.Fill(table)
TextBox1.Text = ""
TextBox2.Text = ""
TextBox3.Text = ""
TextBox4.Text = ""
If table.Rows.Count() > 0 Then
TextBox1.Text = table.Rows(0)(1).ToString
TextBox2.Text = table.Rows(0)(2).ToString
TextBox3.Text = table.Rows(0)(3).ToString
TextBox4.Text = table.Rows(0)(4).ToString
Else
MessageBox.Show("NO DATA FOUND!!")
End If
End Sub
Try to change this:
Dim command As New SqlCommand("select * from Medicines where MedicineName ='" & TextBox1.Text & "' ", connection)
command.Parameters.Add("#Textbox1",SqlDbType.Text)Value=TextBox1.Text
Into this:
Dim command As New SqlCommand("select * from Medicines where MedicineName = #MedicineName", connection)
command.Parameters.Add("#MedicineName",SqlDbType.Text).Value=TextBox1.Text
This is because you have not declared the parameter name into your original SQL string, then on the second line of your code, before Value, you're missing a dot.
I have my code VB.NET code for the login page like this:
Private Sub OK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OK.Click
Try
If UsernameTextBox.Text = "" Then
MsgBox("Insert your username.")
UsernameTextBox.Focus()
Return
ElseIf PasswordTextBox.Text = "" Then
MsgBox("Insert your Passwprd.")
PasswordTextBox.Focus()
Return
Else
Dim count As Integer
Using con As New OleDbConnection("Provider=SQLOLEDB;Data Source=JUNIOR-PC\SQLEXPRESS;Integrated Security=SSPI;Initial Catalog=ShopHereNow")
con.Open()
Dim command = New OleDbCommand("Select count(*) from Employees where FirstName = '" & UsernameTextBox.Text & "' and [Password] = '" & PasswordTextBox.Text & "'")
count = command.ExecuteNonQuery()
con.Close()
If count > 0 Then
MsgBox("Welcome " & UsernameLabel.Text & "!")
Me.Hide()
Home.Show()
Else
MessageBox.Show("Invalid combination. Try again...")
Cancel.PerformClick()
Return
End If
End Using
End If
Catch ex As Exception
MessageBox.Show(ex.Message, "ERROR5", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
On executing this code i get the error reading: ExecuteNonQuery: Connection property has not been initialized
Please help, where could I have coded a mistake?
Your code have some mistakes,
Use Parameterized Queries :
Dim command = New OleDbCommand("Select count(*) from Employees where FirstName =#FirstName and Password = #Password")
command.Parameters.AddWithValue("#FirstName", UsernameTextBox.Text)
command.Parameters.AddWithValue("#Password", PasswordTextBox.Text)
This is to avoid SQL Injection Attack AKA For Security
The error mentioned above is because you haven't specify the connection in your command, change your Dim command = New OleDbCommand("Select count(*) from Employees where FirstName =#FirstName and Password = #Password") to Dim command = New OleDbCommand("Select count(*) from Employees where FirstName =#FirstName and Password = #Password", **con**)
MsgBox() is a deprecated method, use MessegeBox.Show() instead.
Do not use Class Exception. Instead specify the specific Exception type. In here, you may need SQLException
I have a forum where I want the user to type a profile name and then click Add and then it will add what they typed in the text box the the ProfileName field in my table. When I click the Add button, it comes up with an error that says An unhandled exception of type System.Data.OleDb.OleDbException occurred in system.data.dll. Here is my code:
Private Sub RefreshData()
Dim cnn As New OleDb.OleDbConnection
If Not cnn.State = ConnectionState.Open Then
cnn.Open()
End If
Dim da As New OleDb.OleDbDataAdapter("SELECT id AS [ID], " & _
"ProfileName AS [Name] " & _
" FROM Profile ORDER BY id", cnn)
Dim dt As New DataTable
da.Fill(dt)
cnn.Close()
Me.dgvData.DataSource = dt
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If (TextBox1.Text = "") Then
MsgBox("Please enter a profile name.")
Else
Dim cnn As New OleDb.OleDbConnection("Provider=Microsof… Source=c:\Data\Database.mdb ;Extended Properties=Paradox 5.x;")
Dim cmd As New OleDb.OleDbCommand
If Not cnn.State = ConnectionState.Open Then
cnn.Open()
End If
cmd.Connection = cnn
cmd.CommandText = "INSERT INTO Profile(ProfileName) " & _
"VALUES (" & Me.TextBox1.Text & "')"
cmd.ExecuteNonQuery()
cnn.Close()
Dim oForm As addsnake
oForm = New addsnake
oForm.Show()
oForm = Nothing
Me.Close()
End If
End Sub
Without further information I suggest that:
You don't need to give id an alias of ID:
SELECT id AS [ID]
you might still enclose it in square-brackets though, if you like:
SELECT [id]
You are missing an apostrophe in the following line:
"VALUES (" & Me.TextBox1.Text & "')"
Also check your connection string at connectionstrings.com