syntax error in FROM clause in vb.net - vb.net

Dim nm As String
Dim pass As String
nm = TextBox1.Text
pass = TextBox2.Text
Try
cn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Pavilion\Documents\Visual Studio 2010\Projects\WindowsApplication5\Ent.accdb"
cn.Open()
Dim sql As String
sql = "SELECT * FROM user WHERE UName='" & nm & "'AND Pwd='" & pass & "'"
cmd = New OleDbCommand(sql, cn)
dr = cmd.ExecuteReader
While (dr.Read())
If ((nm.Equals(dr(0))) And pass.Equals(dr(1))) Then
MessageBox.Show("Login Sucessful")
End If
End While
Catch ex As Exception
MsgBox("Login Failed :" & ex.Message)
End Try
This code is giving the following error syntax error in FROM clause

#Tim is correct, but I think you might also have problem with your SQL as user is a reserved word. If I execute
SELECT * FROM user WHERE UName='fred' AND Pwd='123'
in SQL Server
I get told Incorrect syntax near the keyword 'user'.
You can overcome this by putting [] around the tablename, i.e.
Select * FROM [user] WHERE UName='fred' AND Pwd='123'

If the code you posted is copy and paste, you're missing a space between the username and the AND keyword.
Your code:
"SELECT * FROM user WHERE UName='" & nm & "'AND Pwd='" & pass & "'"
Should be:
"SELECT * FROM user WHERE UName='" & nm & "' AND Pwd='" & pass & "'"
However, you should use parameterized queries to avoid the possibility of SQL injection attacks. Something like this:
sql = "SELECT * FROM user WHERE UName=#nm AND Pwd=#pass"
cmd = New OleDbCommand(sql, cn)
cmd.Parameters.AddWithValue("#nm", TextBox1.Text)
cmd.Parameters.AddWithValue("#pass", TextBox2.Text)
cmd.CommandType = CommandType.Text
dr = cmd.ExecuteReader

Try
cn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Pavilion\Documents\Visual Studio 2010\Projects\WindowsApplication5\Ent.accdb"
cn.Open()
Dim sql As String
sql = "SELECT * FROM user WHERE UName='" + nm + "'AND Pwd='" + pass + "'"
cmd = New OleDbCommand(sql, cn)
dr = cmd.ExecuteReader
While (dr.Read())
If ((nm.Equals(dr(0))) And pass.Equals(dr(1))) Then
MessageBox.Show("Login Sucessful")
End If
End While
Catch ex As Exception
MsgBox("Login Failed :" & ex.Message)
End Try

"SELECT Firstname FROM [RegUser] where Firstname=#d3 and password=#d4"
i just enclose my table name into brackets and its done.. it works actually
i hope this will help you a lot..

Related

Error when saving from format(val(textbox.text), "#,##0") to numeric field type in SQL

In SQL Server, I have a table like this:
tableItem
------------------------
item | varchar (15),
price | numeric(18, 2)
In VB.NET, I have the code:
textbox1.text = "Book"
textbox2.text = 20.000,00
textbox2.text = format(val(textbox2.text), "#,##0.00")
Procedure Save :
dim sqlQuery as string = "insert into tableItem(item,price) values('" & textbox1.Text & "','" & textbox2.Text & "')"
Try
conn.open()
With Cmd
.Connection = Conn
.CommandType = CommandType.Text
.CommandText = sqlQuery
.ExecuteNonQuery
End With
Catch ex As Exception
MsgBox("Error at : " & ex.Message)
Finally
conn.close()
End Try
but I am getting the error:
Error converting data type varchar to numeric
If I change & textbox2.Text & to & val(textbox2.text) & in the query, the data is stored only 20 in price.
you are not allowed to assign 20.000,00 to a textbox2.Text property.
Try:
textbox2.text = "20.00"
On another note I would not pass the variables directly into the SQL insert query. Try the code below:
dim sqlQuery as string = "insert into tableItem(item,price) values(#item, #price)"
Try
conn.open()
With Cmd
.Parameters.AddWithValue("#item, textbox1.text)
.Parameters.AddWithValue("#price, textbox2.text)
.Connection = Conn
.CommandType = CommandType.Text
.CommandText = sqlQuery
.ExecuteNonQuery
End With
Catch ex As Exception
MsgBox("Error at : " & ex.Message)
End Try
conn.close()
Thanks for the help, but I found another way to keep using
format(val(texbox2.text), "#,##0")
on the keypress
and return to its original value (integer) using
Format(texbox2.text, "General Number")
I found this answer from other similar people's questions.
Thanks very much.

Solve error in update query

I have code that throws an error - I need your help to solve it.
The error is
Syntax error in update statement
My code:
Try
Dim conn As OleDbConnection = New OleDbConnection(My.Resources.ConnectionString)
Dim cmd As OleDbCommand
conn.Open()
Dim Sql As String = "select * from Administretor"
cmd = New OleDbCommand(Sql, conn)
Dim userE, userR As String
userE = txtOldPass.Text
Dim reder As OleDbDataReader = cmd.ExecuteReader()
While reder.Read()
userR = reder.Item(0)
End While
If userE = userR Then
If txtNewPass.Text = txtNewConfromPass.Text And txtNewConfromPass.Text <> "" And txtNewPass.Text <> "" Then
Sql = "UPDATE Administretor SET PASSWORD='" & txtNewPass.Text & " where LogIn_id=" & txtOldPass.Text & ""
Dim cmd0 As OleDbCommand = New OleDbCommand(Sql, conn)
cmd0.ExecuteNonQuery()
Else
MsgBox("Make sure that you have entered new password in both text Box and they both are same...!")
End If
Else
MsgBox("Enter the correct Username")
End If
MsgBox("Done 2")
Catch ex As OleDbException
MsgBox(ex.Message)
End Try
Two errors
"UPDATE Administretor SET PASSWORD='" & txtNewPass.Text & " where LogIn_id=" & txtOldPass.Text & ""
^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
| |
Missing single quote here---+ |
|
LogIn_Id will never equal the old password--------------------------------+
But apart from the simple syntax errors you have a huge SQL injection vulnerability from building the SQL out of pieces including user input.
In this part,
"UPDATE Administretor SET PASSWORD='" & txtNewPass.Text & " where ...
The PASSWORD will have a single quote before it, and no single quote after it.
Change it to:
"UPDATE Administretor SET PASSWORD='" & txtNewPass.Text & "' where ...
Notice the extra single quote here ----------------------------------------^
Add this syntax :
Sql = "UPDATE Administretor SET PASSWORD='" & txtNewPass.Text & " where LogIn_id=" & txtOldPass.Text & ""
Clipboard.SetText(Sql)
The query will be in your clipboard. Run it on SQL(whichever you are using), and see if the query runs smoothly?
Please show us what the query generation holds and what the error it produce when running directly from the SQL.

ExecuteReader: CommandText property has not been initialized when trying to make a register form for my database

hello guys im trying to script a register form for my database and i came with this code >> so can anyone help ?
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim cn As New SqlConnection
Dim cmd As New SqlCommand
Dim dr As SqlDataReader
cn.ConnectionString = "Server=localhost;Database=test;Uid=sa;Pwd=fadyjoseph21"
cmd.Connection = cn
cmd.CommandText = "INSERT INTO test2(Username,Password) VALUES('" & TextBox1.Text & "','" & TextBox2.Text & "')"
cn.Open()
dr = cmd.ExecuteReader
If dr.HasRows Then
MsgBox("You're already registered")
Else
MsgBox("Already registered")
End If
End Sub
Edit your Code in this way..
cmd.CommandText = "INSERT INTO User_Data(Username,Password) VALUES('" & TextBox1.Text & "' , '" & TextBox2.Text & "')"
cn.Open()
cmd.ExecuteNonQuery()
cn.Close()
Insert will not retrieve any records it's a SELECT statement you want to use .I'll suggest you use stored procedures instead to avoid Sql-Injections.
ExecuteReader it's for "SELECT" queries, that helps to fill a DataTable. In this case you execute command before cmd.commandText is defined.
You should have define cmd.commandText before and use ExecuteNonQuery after, like this.
Dim cn As New SqlConnection
Dim cmd As New SqlCommand
cn.ConnectionString = "Server=localhost;Database=test;Uid=sa;Pwd=fadyjoseph21"
cmd.Connection = cn
cn.Open()
cmd.CommandText = "INSERT INTO User_Data(Username,Password) VALUES('" & TextBox1.Text & "','" & TextBox2.Text & "')"
cmd.ExecuteNonQuery()
cn.Close()
cmd.CommandText should be assigned stored proc name or actual raw SQL statement before calling cmd.ExecuteReader
Update:
Change code as follows
....
cmd.Connection = cn
cmd.CommandText = "select * from TblToRead where <filter>" ''This is select query statement missing from your code
cn.Open()
dr = cmd.ExecuteReader ....
where <filter> will be something like username = "' & Request.form("username') & '" '
The error itself is happening because you're trying to execute a query before you define that query:
dr = cmd.ExecuteReader
'...
cmd.CommandText = "INSERT INTO User_Data(Username,Password) VALUES('" & TextBox1.Text & "' and '" & TextBox2.Text & "')"
Naturally, that doesn't make sense. You have to tell the computer what code to execute before it can execute that code:
cmd.CommandText = "INSERT INTO User_Data(Username,Password) VALUES('" & TextBox1.Text & "' and '" & TextBox2.Text & "')"
'...
dr = cmd.ExecuteReader
However, that's not your only issue...
You're also trying to execute a DataReader, but your SQL command doesn't return data. It's an INSERT command, not a SELECT command. So you just need to execute it directly:
cmd.CommandText = "INSERT INTO User_Data(Username,Password) VALUES('" & TextBox1.Text & "' and '" & TextBox2.Text & "')"
cmd.ExecuteNonQuery
One value you can read from an INSERT command is the number of rows affected. Something like this:
cmd.CommandText = "INSERT INTO User_Data(Username,Password) VALUES('" & TextBox1.Text & "' and '" & TextBox2.Text & "')"
Dim affectedRows as Int32 = cmd.ExecuteNonQuery
At this point affectedRows will contain the number of rows which the query inserted successfully. So if it's 0 then something went wrong:
If affectedRows < 1 Then
'No rows were inserted, alert the user maybe?
End If
Additionally, and this is important, your code is wide open to SQL injection. Don't directly execute user input as code in your database. Instead, pass it as a parameter value to a pre-defined query. Basically, treat user input as values instead of as executable code. Something like this:
cmd.CommandText = "INSERT INTO User_Data(Username,Password) VALUES(#Username,#Password)"
cmd.Parameters.Add("#Username", SqlDbType.NVarChar, 50).Value = TextBox1.Text
cmd.Parameters.Add("#Password", SqlDbType.NVarChar, 50).Value = TextBox2.Text
(Note: I guessed on the column types and column sizes. Adjust as necessary for your table definition.)
Also, please don't store user passwords as plain text. That's grossly irresponsible to your users and risks exposing their private data (even private data on other sites you don't control, if they re-use passwords). User passwords should be obscured with a 1-way hash and should never be retrievable, not even by you as the system owner.
You're attempting to change the CommandText after you're executing your query.
Try this:
Private cn = New SqlConnection("Server=localhost;Database=test;UID=sa;PWD=secret")
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim cmd As New SqlCommand
cmd.CommandText = "select * from table1" ' your sql query selecting data goes here
Dim dr As SqlDataReader
cmd.Connection = cn
cn.Open()
dr = cmd.ExecuteReader
If dr.HasRows = 0 Then
InsertNewData(TextBox1.Text, TextBox2.Text)
Else
MsgBox("Already registered")
End If
End Sub
Private Sub InsertNewData(ByVal username As String, ByVal password As String)
Dim sql = "INSERT INTO User_Data(Username,Password) VALUES(#Username, #Password)"
Dim args As New List(Of SqlParameter)
args.Add(New SqlParameter("#Username", username))
args.Add(New SqlParameter("#Password", password))
Dim cmd As New SqlCommand(sql, cn)
cmd.Parameters.AddRange(args.ToArray())
If Not cn.ConnectionState.Open Then
cn.Open()
End If
cmd.ExecuteNonQuery()
cn.Close()
End Sub
This code refers the INSERT command to another procedure where you can create a new SqlCommand to do it.
I've also updated your SQL query here to use SqlParameters which is much more secure than adding the values into the string directly. See SQL Injection.
The InsertNewData method builds the SQL Command with an array of SQLParameters, ensures that the connection is open and executes the insert command.
Hope this helps!

SQL injection-proofing TextBoxes

I've found some tutorials on this already, but they aren't exactly what I'm looking for, I can use the following for username fields and password fields
Private Sub UsernameTextBox_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles UsernameTextBox.KeyPress
If Char.IsDigit(e.KeyChar) OrElse Char.IsControl(e.KeyChar) OrElse Char.IsLetter(e.KeyChar) Then
e.Handled = False
Else
e.Handled = True
End If
End Sub
But for an email field how would I go about protecting against SQL injection for that textbox, as some email accounts have periods or dashes in them?
Update:
Below is an example of an insert statement I use.
Dim con As SqlConnection
con = New SqlConnection()
Dim cmd As New SqlCommand
Try
con.ConnectionString = "Data Source=" & Server & ";Initial Catalog=" & Database & ";User ID=" & User & ";Password=" & Password & ";"
con.Open()
cmd.Connection = con
cmd.CommandText = "INSERT INTO TB_User(STRUserID, password, Email) VALUES('" & UsernameTextBox.Text & "', '" & MD5Hash(PasswordTextBox.Text) & "', '" & EmailTextBox.Text & "')"
cmd.ExecuteNonQuery()
Catch ex As Exception
MessageBox.Show("Error while inserting record on table..." & ex.Message, "Insert Records")
Finally
con.Close()
End Try
So I need to run this with parametrized queries rather than how I'm doing it now?
Instead of filtering out "invalid" data from user input, consider using parametrized queries and not putting user input directly into your queries; that's very bad form.
To run your current query using parameters, it's pretty easy:
Dim con As New SqlConnection()
Dim cmd As New SqlCommand()
Try
con.ConnectionString = "Data Source=" & Server & ";Initial Catalog=" & Database & ";User ID=" & User & ";Password=" & Password & ";"
con.Open()
cmd.Connection = con
cmd.CommandText = "INSERT INTO TB_User(STRUserID, password, Email) VALUES(#username, #password, #email)"
cmd.Parameters.Add("#username", SqlDbType.VarChar, 50).Value = UsernameTextBox.Text
cmd.Parameters.Add("#password", SqlDbType.Char, 32).Value = MD5Hash(PasswordTextBox.Text)
cmd.Parameters.Add("#email", SqlDbType.VarChar, 50).Value = EmailTextBox.Text
cmd.ExecuteNonQuery()
Catch ex As Exception
MessageBox.Show("Error while inserting record on table..." & ex.Message, "Insert Records")
Finally
con.Close()
End Try
All you have to do is use cmd.Parameters.Add with a parameter name and the right database type (the ones I guessed probably don't match up, so you'll want to change them), then set the value to the value you want used in the query. Parameter names start with an #.
It doesn't depend on the textbox. Don't compose a sql sentence joining strings like this:
"SELECT * FROM User WHERE UserName=" + tbName.Text + ...
Use stored procedures or parameterized queries and you'll be safe from SQL injection.
When you use parameters, the textbox content is used as a value, so it doesn't matter what it contains.
Use a parametrized query like this:
Using conn = New SqlConnection("some connection string")
Using cmd = New SqlCommand("SELECT Password FROM tblUser WHERE UserName = #Name", conn)
cmd.Parameters.Add(New SqlParameter("Name", UsernameTextBox.Text))
conn.Open()
Dim password As String = DirectCast(cmd.ExecuteScalar(), String)
Console.WriteLine(password)
End Using
End Using
This is injection safe!

Data Reader formatting output

I'm using the following function to generate a list of users connected to a selected database. How would I change this to a single line for multiple identical results?
For example: "sa (3) - MYCOMPUTER" rather than listing "sa - MYCOMPUTER" three times?
Function ConnectedUsers(ByVal SelectedDatabase As String, ByVal SelectedInstance As String)
Dim myCommand As SqlCommand
Dim dr As SqlDataReader
Dim mystring As String = String.Empty
Try
Dim myConn As New SqlConnection(ConnectionString)
myConn.Open()
myCommand = New SqlCommand("select loginame,hostname from sysprocesses where db_name(dbid) = '" & SelectedDatabase & ";", myConn)
dr = myCommand.ExecuteReader()
While dr.Read()
mystring += GetFullName(dr(0).ToString().Trim()) & " - " & dr(1).Trim() & vbCrLf
End While
dr.Close()
myConn.Close()
Catch e As Exception
MessageBox.Show(e.Message)
End Try
Return mystring
End Function
Thanks.
The SQL Command should be
select loginame, count(*) as Nbr, hostname from sysprocesses where db_name(dbid) = '" & SelectedDatabase & "' group by loginame;"
and you should change the display to show the count (Nbr in this example) to be something like:
mystring += GetFullName(dr(0).ToString().Trim()) & "(" & dr(1).Trim() & ") - " & dr(2).Trim() & vbCrLf