Home > Software engineering >  System.Data.SqlClient.SqlException: 'Incorrect syntax near ' and password ='.'
System.Data.SqlClient.SqlException: 'Incorrect syntax near ' and password ='.'

Time:02-02

enter image description here

appears when the login form is used. I don't see any issue with the syntax...

And I have no idea how to fix this error, I have looked online and tried different ways to fix it and none of them helped or fixed the problem.

I'm new to this so please excuse me if the error is obvious!

CodePudding user response:

As stated in the other comments this is a bad practice and should be avoided for security reasons (SQL injection), but to answer the question about the error itself, as mentioned by @userMT you are missing single quotes and should be fixed by writing the query as follows:

"select count(*) from [User] where username = '"   username   "' and password = '"   password   "'"

CodePudding user response:

You build the query in your code. Did you actually LOOK at the string you built? Using the values "bob" and "secret" as name and password, it will be in the form:

select count(*) from [User] where username =bob' and password ='secret

Now do you see the problem? And generally speaking, you should not COUNT to know if rows exist. Use the EXISTS function. Here it likely doesn't make much difference but it can if you apply this pattern without thinking.

But as already stated, don't inject values into a query. Parameterize the query properly.

  •  Tags:  
  • Related