Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

public static void UpdateLastLogin(int userid, DateTime logintime) ///logintime = DateTime.Now
{
    string sql = @"UPDATE [Customers] SET [LastLogin]=?";
    OleDbParameter[] prms = new OleDbParameter[] { 
     new OleDbParameter("@LastLogin",logintime)
    };
    using (DAL dal = new DAL())
    {
        dal.UpdateRow(sql, false, prms);
    }
}

When it comes to Dates, I having trouble. This throws a "Data type mismatch in criteria expression." error. (I removed WHERE clause for keeping it simpler) Am I suuposed to enclose [LastLogin]=? question mark with single quotes, # signs .. does not help. Any leads on how to handle DateTime objects with Access and OleDb provider will be greatly appreciated.

Thanks in advance.

like image 316
emre Avatar asked Oct 16 '09 12:10

emre


2 Answers

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")
like image 200
Rinat Abdullin Avatar answered Nov 12 '22 07:11

Rinat Abdullin


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;
like image 37
Cyril Gupta Avatar answered Nov 12 '22 07:11

Cyril Gupta