简体   繁体   English

日期时间数据类型不匹配访问

[英]Date time Data type mismatch access

I am having a problem with this statement i am Trying to retrieve data from a table based on the date but its keep telling me that there is a data type mismatch 我对此语句有疑问,我正在尝试根据日期从表中检索数据,但它不断告诉我数据类型不匹配

DateTime dt = DateTime.ParseExact(textBox1.Text, "dd/mm/yyyy", null);
            OleDbCommand cmd2 = new OleDbCommand("select name from Items where exp_dat='" + dt + "'", con);
            System.Data.DataTable dt4 = new System.Data.DataTable();
            OleDbDataAdapter Adapter4 = new OleDbDataAdapter(cmd2);
            Adapter4.Fill(dt4);
            dataGridView1.DataSource = dt4;

Use parameters to prevent sql injection and conversion/localization issues: 使用参数来防止sql注入和转换/本地化问题:

var dt4 = new System.Data.DataTable();
using(var da = new OleDbDataAdapter("select name from Items where exp_dat=@exp_dat", con))
{
    DateTime dt;
    if(DateTime.TryParseExact(textBox1.Text, "dd/mm/yyyy", DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None, out dt))
    {
        da.SelectCommand.Parameters.Add("@exp_dat", OleDbType.Date).Value = dt;
        da.Fill( dt4 );
    }
}

Note that 注意

  • con.Open / con.Close is not needed with OlebDataAdapter.Fill(table) OlebDataAdapter.Fill(table)不需要con.Open / con.Close
  • you should always use the using -statement on objects that are disposable(implement IDisposable ), that ensures that all unmanaged resources are disposed, even in case of an error 您应该始终在可抛弃的对象上使用using -statement(实现IDisposable ),以确保即使在发生错误的情况下也可以处置所有非托管资源
  • you should use DateTimeFormatInfo.InvariantInfo or CultureInfo.InvariantCulture instead of null as parameter for ParseExact since null is replaced with the current culture. 您应使用DateTimeFormatInfo.InvariantInfoCultureInfo.InvariantCulture代替null作为ParseExact参数,因为将null替换为当前区域性。 If that does not use / as date separator TryParseExact cannot parse this string(presuming that textBox1.Text is something like 28/09/2015 ) 如果该方法不使用/作为日期分隔符,则TryParseExact无法解析此字符串(假定textBox1.Text类似于28/09/2015

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM