c# - SQL Request with Timestamp -
i'm using c# request sql server. request need between 2 timestamps (date , hour). problem if put date (2015-04-15) works if put time behind (2015-04-15 16:00:00) doesn't work anymore , show error : "close '16' syntax incorrect."
i try different things can't find way.
here code:
datetime endtime = convert.todatetime(datetime.now.date.tostring("d") + " " + datetime.now.addhours(1).hour.tostring("00") + ":00:00"); datetime starttime = convert.todatetime(datetime.now.date.tostring("d") + " " + datetime.now.hour.tostring("00") + ":01:00"); string time = string.empty; sqlconnection sqlcon = new sqlconnection("..."); sqlcon.open(); sqlcommand sqlcmd = new sqlcommand("select count(timestamp) net timestamp between " + starttime.tostring("yyyy-mm-dd hh:mm:ss") + " , " + endtime.tostring("yyyy-mm-dd hh:mm:ss"), sqlcon); sqldatareader reader = sqlcmd.executereader(); //error comes here while (reader.read()) { time = reader[0].tostring(); } console.writeline(time);
do have idea make it?
how making parameterized query, in:
// somewhere in class declaration: // fixed parameterized query text constant. private const string timerangequerysql = "select count(timestamp) net timestamp between @starttime , @endtime"; // ... var cmd = new sqlcommand(timerangequerysql, sqlcon); cmd.parameters.add("@starttime", sqldbtype.datetime).value = starttime; cmd.parameters.add("@endtime", sqldbtype.datetime).value = endtime; var reader = sqlcmd.executereader(); // ...
note practice use parameterized queries instead of trying assemble query string yourself, don't expose sql injection attacks. may want read story of little bobby tables.
Comments
Post a Comment