robert
robert

Reputation: 321

Inserting a date/time value in Access using an OleDbParameter

I'm trying to do an insert in oledb(ms access database) the field called objectdate is date/time

the code i use to add the parameter is this, but i'm getting error.

  OleDbParameter objectdate = new OleDbParameter("@objectdate", OleDbType.DBDate);
  objectdate.Value = DateTime.Now; cmd.Parameters.Add(objectdate);

the error:

Data type mismatch in criteria expression.

Upvotes: 6

Views: 11540

Answers (4)

HackSlash
HackSlash

Reputation: 5805

When using OleDb in .netstandard2.0 you can add using the .AddWithValue with just a key value pair. The type is inferred from the value object:

cmd.Parameters.AddWithValue("@objectdate", DateTime.Now)

Do not convert to string because that would destroy the ability to infer type.

Upvotes: 0

Wout
Wout

Reputation: 621

OleDB doesn't like milliseconds in the datetime parameters. If you remove the milliseconds it will go ok. See also: How to truncate milliseconds off of a .NET DateTime.

Upvotes: 10

Alfonso
Alfonso

Reputation: 1

The sentence:

OleDbParameter objectdate = new OleDbParameter("@objectdate", DbType.DateTime);

is not acepted in visual basic 2008, I use like this:

ordeen.Parameters.Add(New OleDb.OleDbParameter("objectdate", DbType.DateTime))
ordeen.Parameters("objectdate").Value=object.text   'but its not run

the next sentence only functional in sqlserver:

cmd.Parameters.AddWithValue("@objectdate", DateTime.Now.ToString());

the problem in Access continued yet

Upvotes: 0

scartag
scartag

Reputation: 17680

You could use.

   OleDbParameter objectdate = new OleDbParameter("@objectdate", DbType.DateTime);
   objectdate.Value = DateTime.Now; cmd.Parameters.Add(objectdate);

or use the Ole Automation version of the date.

OleDbParameter objectdate = new OleDbParameter("@objectdate", DbType.DateTime);
       objectdate.Value = DateTime.Now.ToOADate(); cmd.Parameters.Add(objectdate);

Or you could enter the datetime as a literal since the Datetime.ToString() removes the milliseconds that access can't work with.

cmd.Parameters.AddWithValue("@objectdate", DateTime.Now.ToString());

this should work.

Upvotes: 0

Related Questions