Data type mismatch in criteria expression | Access, OleDb, C#

前端 未结 6 622
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-06 07:44

I read/update data from MS Access using C#. My code is:

public static void UpdateLastLogin(int userid, DateTime logintime) ///logintime = DateTime.Now
{
             


        
相关标签:
6条回答
  • 2020-12-06 08:15

    Firstly, no your SQL statement should be:

    "UPDATE Customers SET LastLogin=@LastLogin"
    

    Secondly, the reason you are receiving the date mismatch error will probably be your passing '?' as your date time into the LastLogin field instead of the actual logintime parameter.

    0 讨论(0)
  • 2020-12-06 08:18

    Try setting the "DBTYPE" property of the parameter to identify it as a date, datetime or datetime2 as appropriate...

    prms[0].DbType = DbType.DateTime;
    

    There are 7 signatures to the new OleDbParameter() call, so you may change the signature instance, or just do explicitly as I sampled above since you only had 1 parameter in this case.

    0 讨论(0)
  • 2020-12-06 08:22

    maybe try

    DateTime.Now.ToShortDateString() + ' ' + DateTime.Now.ToShortTimeString()
    

    instead, pass it as String (and maybe enclose with # then)

    0 讨论(0)
  • 2020-12-06 08:23

    I solved this using the following code

    OleDbCommand cmd = new OleDbCommand(qry, cnn);
    cmd.Parameters.Add("datenow", OleDbType.Date);
    cmd.Parameters["datenow"].Value = DateTime.Now;
    
    0 讨论(0)
  • 2020-12-06 08:30

    Should it not be

    "UPDATE Customers SET LastLogin='@LastLogin'"
    

    And @LastLogin should be

    logintime.ToString("yyyy-MM-dd hh:mm:ss")
    

    edit Could you not just inline the whole thing?

    "UPDATE Customers SET LastLogin='" + logintime.ToString("yyyy-MM-dd hh:mm:ss") + "'"
    
    0 讨论(0)
  • 2020-12-06 08:33

    There is a known issue with OleDb and dates. Try doing something like:

    OleDbParameter p = parameter as OleDbParameter;
    if (null == p)
      parameter.DbType = DbType.DateTime;
    else
      p.OleDbType = OleDbType.Date;
    

    Or use explicit format string:

    value.ToString("yyyy-MM-dd hh:mm:ss")
    
    0 讨论(0)
提交回复
热议问题