我正在用C#开发一个Windows窗体应用程序。我有一个查询,我想从日期到日期进行选择。结果始终为0。 我的DB是一个.sdf文件,在我的表中我有一个datetime字段,用于存储订单日期为DateTime.Now,我的PC日期格式为10.12.2014, 任何人都可以帮助我解释为什么这个hapening ..!是否有更好的文件格式可以在本地保存。应用程序将安装在几台PC上,日期时间格式是否有问题。你的帮助非常适合..检查请提供一些代码。
internal static DataTable SearchItemsInOrders(string searchWord, string table, int minValue, int maxValue, out DataTable dtTable, DateTime dateFrom, DateTime dateTo)
{
string commandText = "select A.ItemName, B.Site, B.OrderId, A.Qty, B.Requester, B.Receiver, B.Date ";
commandText += "From tblOrderLine AS A Inner join tblOrder As B on A.OrderId=B.OrderId ";
commandText += "where A.ItemName='" + searchWord + "' and B.Date >= '" + dateFrom.ToShortDateString() + "' and B.Date <='" + dateTo.ToShortDateString() + "' Order By A.OrderId DESC";
SqlCeDataAdapter adp = new SqlCeDataAdapter();
SqlCeConnection con = ConAndData.Con;
dtTable = new DataTable();
adp = new SqlCeDataAdapter(commandText, con);
if (con.State == System.Data.ConnectionState.Closed)
{
con.Open();
}
adp.Fill(minValue, maxValue, dtTable);
return dtTable;
}
答案 0 :(得分:1)
尝试使用此查询
string commandText = "select A.ItemName, B.Site, B.OrderId, A.Qty, B.Requester, B.Receiver, B.Date ";
commandText += "From tblOrderLine AS A Inner join tblOrder As B on A.OrderId=B.OrderId ";
commandText += "where A.ItemName='" + searchWord + "' and CONVERT(NVARCHAR(10),B.Date,121) >= CONVERT(NVARCHAR(10),'" + dateFrom.ToString("yyyy-MM-dd") + "',121) and CONVERT(NVARCHAR(10),B.Date,121) <= CONVERT(NVARCHAR(10),'" + dateTo.ToString("yyyy-MM-dd") + "',121) Order By A.OrderId DESC";
希望这会有所帮助......
答案 1 :(得分:0)
正如评论中建议的那样 - 您必须使用参数化查询。
所以,你的commandText应该是:
string commandText = "select A.ItemName, B.Site, B.OrderId, A.Qty, B.Requester, B.Receiver, B.Date ";
commandText += "From tblOrderLine AS A Inner join tblOrder As B on A.OrderId=B.OrderId ";
commandText += "where A.ItemName=@ItemName and B.Date >= @DateFrom and B.Date <=@DateTo Order By A.OrderId DESC";
以后您应该为命令添加参数和值:
adp = new SqlCeDataAdapter(commandText, con);
adp.SelectCommand.Parameters.Add("@ItemName", SqlDbType.NVarChar).Value = searchWord;
adp.SelectCommand.Parameters.Add("@DateFrom", SqlDbType.DateTime).Value = dateFrom;
adp.SelectCommand.Parameters.Add("@DateTo", SqlDbType.DateTime).Value = dateTo;
这也可以防止由ToShortDateString()生成的日期格式错误导致的问题。