我使用C#向SQL服务器发出请求。请求需要在2个时间戳(日期和小时)之间。问题是如果我只把日期(2015-04-15)它有效但如果我把时间推迟(2015-04-15 16:00:00)它不再工作并显示错误:&# 34;接近' 16'语法不正确。"
我尝试不同的东西,但我找不到方法。
这是我的代码:
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) FROM net WHERE Timestamp BETWEEN " + Starttime.ToString("yyyy-MM-dd hh:mm:ss") + " AND " + Endtime.ToString("yyyy-MM-dd hh:mm:ss"), sqlCon);
SqlDataReader reader = sqlCmd.ExecuteReader(); //Error comes from here
while (reader.Read())
{
time = reader[0].ToString();
}
Console.WriteLine(time);
你有任何想法吗?
答案 0 :(得分:5)
如何使这成为参数化查询,如:
// Somewhere in your class declaration:
// Fixed parameterized query text as a constant.
private const string TimeRangeQuerySQL =
"SELECT COUNT(TimeStamp) FROM net WHERE Timestamp BETWEEN @starttime AND @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();
// ...
请注意,最好使用参数化查询,而不是尝试自己组装查询字符串,这样就不会让自己暴露于SQL注入攻击。您可能想要阅读little bobby tables的故事。