将datetime转换为varchar时出现上述异常
if (columnDefs[i].IndexOf("Date") > -1)
{
// Date search
subQuery += columnDefs[i] +
" = '%" +
DateTime.Parse(searchValues[i]).ToString("dd/MM/yyyy") +
"'" + " and ";
}
答案 0 :(得分:0)
使用SQL时,不要 hardcode 而是 paramterize 查询;假设您使用的MS SQL具有@parameter_name
语法:
if (columnDefs[i].IndexOf("Date") >= 0)
{
// Date search: we a parameter, not its value into the query
subQuery += $" ({columnDefs[i]} = @prm_{columnDefs[i]}) and ";
}
...
// when executing the query
using (var myQuery = new SqlQuery(subQuery, myConnection)) {
// we set parameters' values
for (int i = 0; i < columnDefs.Count(); ++i) {
if (columnDefs[i].IndexOf("Date") >= 0) {
//TODO: check the actual parameter value type (SqlDbType.DateTime?)
var prm = new SqlParameter($"@prm_{columnDefs[i]}", SqlDbType.DateTime);
//TODO: check actual string format (d/M/yyyy?)
prm.Value = DateTime.ParseExact(
searchValues[i],
"d/M/yyyy",
CutureInfo.InvariantCulture);
myQuery.Parameters.Add(prm);
}
}
...
}