带Access DateTime查询的C#OLEDB参数
我有以下查询,可以从内部访问或从作为OLEDB命令的C#进行查询:带Access DateTime查询的C#OLEDB参数,c#,ms-access,datetime,oledbparameter,C#,Ms Access,Datetime,Oledbparameter,我有以下查询,可以从内部访问或从作为OLEDB命令的C#进行查询: SELECT Table1.ProductType, Sum(Table1.ProductsSold) FROM Table1 WHERE (Table1.DateTime Between #5/16/2013# And #5/17/2013#) GROUP BY Table1.ProductType; 表1.DateTime是日期/时间数据类型 现在我想把日期作为OLEDB参数传递 SELECT Table1.Product
SELECT Table1.ProductType, Sum(Table1.ProductsSold)
FROM Table1
WHERE (Table1.DateTime Between #5/16/2013# And #5/17/2013#)
GROUP BY Table1.ProductType;
表1.DateTime是日期/时间数据类型
现在我想把日期作为OLEDB参数传递
SELECT Table1.ProductType, Sum(Table1.ProductsSold)
FROM Table1
WHERE (Table1.DateTime Between #@StartDate# And #@StopDate#)
GROUP BY Table1.ProductType;
cmd.Parameters.Add(new OleDbParameter("@StartDate", OleDbType.Date));
cmd.Parameters["@StartDate"].Value = dateTimePicker1.Value.ToShortDateString();
cmd.Parameters.Add(new OleDbParameter("@StopDate", OleDbType.Date));
cmd.Parameters["@StopDate"].Value = dateTimePicker2.Value.ToShortDateString();
我已经搜索并尝试了很多东西(VarChar和字符串、单引号而不是hashtags、命令或参数中的hashtags等等),但运气不好。我希望日期从午夜开始(因此是ToSortDateString()和日期类型)。您需要去掉查询文本中的哈希标记(
#
)分隔符。文本SQL查询需要日期的分隔符#
和字符串的分隔符
,但在参数化SQL查询中必须省略。以下是我的工作测试代码供参考:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.OleDb;
namespace oledbTest1
{
class Program
{
static void Main(string[] args)
{
var conn = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\__tmp\testData.accdb;");
conn.Open();
var cmd = new OleDbCommand(
"SELECT Table1.ProductType, SUM(Table1.ProductsSold) AS TotalSold " +
"FROM Table1 " +
"WHERE Table1.DateTime BETWEEN @StartDate AND @StopDate " +
"GROUP BY Table1.ProductType",
conn);
cmd.Parameters.AddWithValue("@StartDate", new DateTime(2013, 5, 16));
cmd.Parameters.AddWithValue("@StopDate", new DateTime(2013, 5, 17));
OleDbDataReader rdr = cmd.ExecuteReader();
int rowCount = 0;
while (rdr.Read())
{
rowCount++;
Console.WriteLine("Row " + rowCount.ToString() + ":");
for (int i = 0; i < rdr.FieldCount; i++)
{
string colName = rdr.GetName(i);
Console.WriteLine(" " + colName + ": " + rdr[colName].ToString());
}
}
rdr.Close();
conn.Close();
Console.WriteLine("Done.");
Console.ReadKey();
}
}
}
当我运行时,MessageBox总是显示类似于
2013-05-01 00:00:00
(而不是当前时间)。我的问题可能没有突出显示问题。我的原始参数类似于cmd.parameters.AddWithValue(“StartDate”,dtpDailyStartDate.Value);但是,DateTimePicker的Value属性返回了正确的日期,但返回了当前时间。这使我尝试了以下方法:cmd.Parameters.AddWithValue(“@StartDate”,Convert.ToDateTime(dateTimePicker1.Value.ToShortDateString());此方法未返回任何记录。如果我将DateTimePicker的Format属性设置为Short,则原始参数将起作用。我将DateTimePicker的格式设置为Custom,将CustomFormat属性设置为dddd、MMM dd、yyyy。“属性”窗口表示该属性控制值的显示方式。它似乎还影响Value属性的返回方式。我真的希望显示工作日,但得到午夜作为时间的值。
DateTime justTheDate = dateTimePicker1.Value.Date;
MessageBox.Show(justTheDate.ToString());