-2

I have a variable string session_start_time which gets result from database and is - 2017-07-15 03:54:37.000

But the following query results in an error:

select * 
from surf_ads_views 
where date_time >= " + session_start_time + " 
  and member_id = " + member_id

The error is below:

An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code

Additional information: Incorrect syntax near '3'.

I am not able to figure out, why its causing an error

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Bangla Tiger
  • 89
  • 2
  • 14
  • 3
    Learn how to use parameters. Do not concatenate strings to form sql commands. It is an infinite source of problems – Steve Jul 14 '17 at 22:29
  • 2
    Possible duplicate of [Pass parameters to SQLCommand?](https://stackoverflow.com/questions/293311/). – Dour High Arch Jul 14 '17 at 22:31
  • yeah as Steve says use parameters and add [ ] around the words which is in DB like name of tables, columns – MiOnIs Jul 14 '17 at 22:54

2 Answers2

2

Your particular issue is that you are injecting the string which needs to be wrapper in single quotes.

...date_time >='" + session_start_time + "' and ... That being said, you should use parameters instead of SQL injection as it will address these types of issues and improve your security.

Babak Naffas
  • 12,395
  • 3
  • 34
  • 49
0

You should change the property type from String to DateTime, and let the data base manage the type as it is configured, and use stored procedure instead of SQL statements

Create procedure dbo.SelectData @StartDate DateTime As select * from surf_ads_views where date_time = @StartDate

Gilberto
  • 77
  • 7