Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL syntax error in Update statement VB.net

I'm getting a strange syntax error when I run this in VB:

        SQLString = "UPDATE Login SET Password = '" + PasswordTextBox.Text + "'"
        SQLString += " WHERE UserName = '" + UserNameTextBox.Text + "'"

The Username is checked before getting to this part and is definitly in the database. It gives an exception saying that there's a syntax error in update statement. Anyone have any idea what's wrong?

like image 353
Shane Fagan Avatar asked Feb 28 '23 09:02

Shane Fagan


1 Answers

LOGIN is a reserved word in SQL Server (used for login account management), so in order to use it in a query (i.e. a column name) you need to escape it with [], so use [LOGIN] as the field name.

You should never use string concatenation and pass that to your SQL database, as you are exposing yourself to SQL Injection attacks.

You should use the SqlCommand object and pass through parameters. See this article on how to do so.

SQLString = "UPDATE [Login] SET Password = @password "
SQLString += " WHERE UserName = @userName"

...

dbCommand.Parameters.Add("@password", SqlDbType.VarChar, 50)
dbCommand.Parameters["@password"].Value = PasswordTextBox.Text

dbCommand.Parameters.Add("@userName", SqlDbType.VarChar, 50)
dbCommand.Parameters["@userName"].Value = UserNameTextBox.Text
like image 118
Oded Avatar answered Mar 01 '23 21:03

Oded