简体   繁体   中英

Passing a DateTime value as a parameter to an OleDbCommand

I have a problem passing a DateTime value to a query as a DbParameter. It seems the time part of the DateTime value gets stripped away.

Here is a sample code in C#:

DbProviderFactory _factory = OleDbFactory.Instance;

DbCommand cmd = _factory.CreateCommand();
cmd.CommandText = "INSERT INTO SomeTable (SomeDateField) VALUES (?)";

DbParameter p = _factory.CreateParameter();
p.ParameterName = ""; // Not necessary
p.Value = DateTime.Now; // assume Time != 00:00:00
p.DbType = DbType.Date; // DateTime and DateTime2 don't work

cmd.Parameters.Add(p);

My problem is that the Date parameter does not seem to reach Access with it's time part and SomeDateField always has 00:00:00 as time.

I don't want to do something like:

cmd.CommandText = "INSERT INTO SomeTable (SomeDateField) VALUES (#" + aDateTimeString + "#)";

OleDbType does not have a DateTime enumeraton http://msdn.microsoft.com/en-us/library/system.data.oledb.oledbtype.aspx

If you use DBType.DateTime, "The type of a parameter is specific to the .NET Framework data provider. Specifying the type converts the value of the Parameter to the data provider Type before passing the value to the data source. If the type is not specified, ADO.NET infers the data provider Type of the Parameter from the Value property of the Parameter object. "http://msdn.microsoft.com/en-us/library/system.data.dbtype.aspx

Make sure your data type for SomeDateField is DateTime and not Date . Also, try to make

p.DbType = DbType.DateTime;

When you'd use OleDbType.DateTime instead of DbType.Date , I'm sure it will work.

But, as I understand from your post, you do not want to be so specific, and use the more general DbType enum (and classes)?

However, I think you should use the more specific OleDb classes in your data-access layer. Using the less specified 'DbType' classes, is kind of useless, because, when you're targetting another database-type, chances are quite big that your SQL-syntax will have to change as well, since each DBMS uses its own dialect (sometimes only minor changes, but still... ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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