为什么 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 连接 > IDbConnection > 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");
更新2
/* 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
*/