Skip to content
Advertisement

SQL query from C#

I am trying to query SQL Server database from C#

I have class

There is a problem in my query.

When I give normal query “select * from table” — this gives me perfect results.

But when I try to give where condition it gives me error. Any suggestions, to fix this? Thanks.

Advertisement

Answer

⚠️ WARNING This answer contains a SQL injection security vulnerability. Do not use it. Consider using a parameterized query instead, as described in some of the other answers to this question (e.g. Tony Hopkinson’s answer).

Try adding quotes around the values in the where clause like this:

In your case where you are using variables you need to add the quotes and then concatenate the values of the variables into the string. Or you could use String.Format like this:

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement