开发者

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.Valu开发者_StackOverflowe = DateTime.Now; cmd.Parameters.Add(objectdate);

the error:

Data type mismatch in criteria expression.


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.


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.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜