为什么IDbDataParameter使用2001年而不是0001更新Access DateTime字段?

时间:2012-12-07 15:05:05

标签: c# ms-access datetime dbtype

为什么IDbDataParameter使用2001年而不是0001更新MS Access DateTime字段? 我正在使用IDbDataParameter。它适用于SQL服务器,但不适用于MS Access。我以为我早些时候测过了......

IDbDataParameter dp;
var dbType = GetDatabaseType(Cmd.Connection);
for (int n = 0; n < Parameters.Length; n++)
{
var param = Parameters[n];
dp = Cmd.CreateParameter();
dp.ParameterName = paramNames[n];
TypeCode myTypeCode = Type.GetTypeCode(param.GetType());
if (myTypeCode == TypeCode.DateTime)     // this workaround is needed for MS Access and SQL Server
{
  if (dbType == DatabaseType.OleDb)
    dp.DbType = DbType.DateTime;         // set dates as DbType.DateTime for MS Access and Paradox
  else if (dbType == DatabaseType.MSSql)
    dp.DbType = DbType.DateTime2;        // set dates as DbType.DateTime2 for SQL Server
  dp.Value = param.ToString();
}
else
  dp.Value = param;
Cmd.Parameters.Add(dp);

UPDATE1 在Access中设置DateTime时有时也会出现错误的时间(OleDb连接&gt; IDbConnection&gt; IDbCommand)

10秒保存为:2001-01-01 00:28:32 // dp.Value = param.ToString();

如果格式化字符串,它也会保存为2001,现在使用12:00中午:2001-01-01 12:00:46 // dp.Value = ConvertToDateTime(param).ToString(“yyyy-MM-dd HH:MM:SS“);

UPDATE2

/* Tests when executing insert and update queries against MS Access (OleDb Jet) and DateTime field using value of '0001-01-01 00:00:00'.
  * DateTime d = Convert.ToDateTime(param);
  * dp.Value = new DateTime(d.Year, d.Month, d.Day, d.Hour, d.Minute, d.Second); // Insert/Update = 2001-01-01
  * dp.Value = Convert.ToDateTime(param).ToString("yyyy-MM-dd hh:mm:ss");        // Insert/Update = 2001-01-01 00:00:00
  * dp.Value = param.ToString();                 // Insert/Update = 2001-01-01
  * dp.Value = Convert.ToDateTime(param);        // Insert/Update = 2001-01-01
  * dp.Value = param;                            // Insert/Update = 2001-01-01
  * dp.Value = new DateTime(1, 1, 1, 0, 0, 0);   // Insert/Update = 2001-01-01
  */

/* Tests when executing query against MS Access (OleDb Jet) and DateTime field using value of '2010-10-10 10:10:10'.
  * DateTime d = Convert.ToDateTime(param);
  * dp.Value = new DateTime(d.Year, d.Month, d.Day, d.Hour, d.Minute, d.Second); // Insert/Update = 2010-10-10 10:10:10
  * dp.Value = Convert.ToDateTime(param).ToString("yyyy-MM-dd hh:mm:ss");        // Insert/Update = 2010-10-10 10:10:10
  * dp.Value = param.ToString();                 // Insert/Update = 2010-10-10 10:10:10
  * dp.Value = Convert.ToDateTime(param);        // Insert/Update = 2010-10-10 10:10:10
  * dp.Value = param;                            // Insert/Update = 2010-10-10 10:10:10
  * dp.Value = new DateTime(2010, 10, 10, 10, 10, 10);   // Insert/Update = 2010-10-10 10:10:10
  */

0 个答案:

没有答案