带有Access DateTime查询的C#OleDbParameter

我有以下查询,从Access内部或从C#作为OleDbCommand:

SELECT Table1.ProductType, Sum(Table1.ProductsSold) FROM Table1 WHERE (Table1.DateTime Between #5/16/2013# And #5/17/2013#) GROUP BY Table1.ProductType; 

Table1.DateTime是日期/时间数据类型。

现在我想将日期作为OleDbParameters传递。

 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和字符串,单引号而不是主题标签,命令或参数中的主题标签等),没有运气。 我希望日期从午夜开始(因此ToShortDateString()和Date类型。)

您需要删除查询文本中的哈希标记( # )分隔符。 文字 SQL查询需要使用#for date和' for strings这样的分隔符,但必须在参数化 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(); } } } 

请注意,我为参数添加了不同的名称(以便更接近地匹配您所做的),但请记住,对于Access OLEDB,参数名称将被忽略 ,参数必须以与它们在命令文本中出现的顺序完全相同的顺序进行定义。

编辑

如果你只想提取DateTimePicker值的Date部分,那么尝试这样的事情:

 DateTime justTheDate = dateTimePicker1.Value.Date; MessageBox.Show(justTheDate.ToString()); 

当我运行它时,MessageBox总是显示类似2013-05-01 00:00:00 (而不是当前时间)。