ACCESS中的"时间/日期"字段中插入DateTime.Now出错
向ACCESS中的"时间/日期"字段中插入DateTime.Now时出现“标准表达式中数据类型不匹配。”错误的解决办法:
在使用下面的代码向Access数据库中添加数据的时候,如果是日期字段,则会出现"标准表达式中数据类型不匹配。"的错误,这可能是C#中的日期类型无法直接转换成Access中的日期类型OleDbType.DBDate所致:
string ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\MengXianHui.mdb;Persist Security Info=True";
string QueryString = "Insert Into [Document] (Title, Content, Author, CreateDate) Values(@Title, @Content, @Author, @CreateDate)";
OleDbConnection cn = new OleDbConnection(ConnectionString);
cn.Open();
OleDbCommand cmd = new OleDbCommand(QueryString, cn);
cmd.Parameters.AddWithValue("@Title", Title);
cmd.Parameters.AddWithValue("@Content", Content);
cmd.Parameters.AddWithValue("@Author", Author);
cmd.Parameters.AddWithValue("@CreateDate", DateTime.Now);
cmd.ExecuteNonQuery();
cn.Close();
cn.Dispose();
string ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\MengXianHui.mdb;Persist Security Info=True";
string QueryString = "Insert Into [Document] (Title, Content, Author, CreateDate) Values(@Title, @Content, @Author, @CreateDate)";
OleDbConnection cn = new OleDbConnection(ConnectionString);
cn.Open();
OleDbCommand cmd = new OleDbCommand(QueryString, cn);
cmd.Parameters.AddWithValue("@Title", Title);
cmd.Parameters.AddWithValue("@Content", Content);
cmd.Parameters.AddWithValue("@Author", Author);
cmd.Parameters.AddWithValue("@CreateDate", DateTime.Now);
cmd.ExecuteNonQuery();
cn.Close();
cn.Dispose();
解决办法就是将上面语句中的 cmd.Parameters.AddWithValue("@CreateDate", DateTime.Now); 转换成下面的语句即可:
OleDbParameter parameter = new OleDbParameter();
parameter.OleDbType = OleDbType.DBDate;
parameter.Value = DateTime.Now;
cmd.Parameters.Add(parameter);