0

朋友们...

在我的 ms 访问数据库中,我存储日期格式 dd-MMM-yy。并在搜索查询中将日期作为参数传递。但是我的系统不能包含日期格式 mm/dd/yyyy 所以,我如何在将这个日期传递给现在查询之前将此格式转换为 dd-MMM-yy,我使用以下代码..但给出错误....字符串无法识别作为有效的日期时间。

DateTime dt = DateTime.ParseExact(startdate.ToString(), "dd-MMM-yy", 
                                  CultureInfo.InvariantCulture);//startdate is datepicker

询问...

s = new OleDbDataAdapter("
      SELECT opd_patient_master.*, patient_operation.* 
      FROM opd_patient_master, patient_operation 
      WHERE opd_patient_master.pid= patient_operation.pid 
         and opd_patient_master.rdid= patient_operation.rdid 
         and odate >= #" + startdate + "# and odate<=# " + enddate + "# 
         and operation= '" + oprtype + "'", mycon);
4

2 回答 2

2

使用参数,不需要转成字符串

using (var cmd = new OleDbCommand("SELECT opd_patient_master.*, patient_operation.* FROM   opd_patient_master, patient_operation where opd_patient_master.pid= patient_operation.pid and   opd_patient_master.rdid= patient_operation.rdid and odate >= ?  and odate<= ? and operation= ?", mycon))
{
    cmd.Parameters.AddWithValue("@startdate", startDateTimePicker.Value); // use DateTime input here as startdate
    cmd.Parameters.AddWithValue("@enddate", endDateTimePicker.Value); // use DateTime input here as enddate
    cmd.Parameters.AddWithValue("@oprtype", oprtype);
    using (OleDbDataAdapter s = new OleDbDataAdapter(cmd))
    {
       // do something with adapter 
    }

}

请注意,您可以DateTime直接从日期时间选择器控件中获取所选值。使用DateTimePicker.Value属性

于 2013-08-27T11:03:53.567 回答
0

使用参数查询是更好的选择,然后将处理这些格式问题。

对于当前的方法,一种解决方案是使用标准 ISO 日期格式 YYYY-MM-DD,将日期作为字符串传递:

string sStartDate = startdate.Value.ToString("yyyy-MM-dd");

".. and odate >= #" + sStartDate + "#..

自定义日期和时间格式:MSDN

于 2013-08-27T11:10:22.707 回答