Wednesday, January 27, 2010

ACCESS to the "time / date" field when you insert a DateTime.Now "Standard expression data type mismatch." Wrong solution

In the Use the following code to add data to the Access database, when, and if the date field, there will be "standard does not match the data type of expression." Error, which may be the date of the type in C # can not be directly converted into Access the date in the type of OleDbType.DBDate result of:

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();


Solution is the above statement cmd.Parameters.AddWithValue ( "@ CreateDate", DateTime.Now); can be converted to the following statement:

OleDbParameter parameter = new OleDbParameter();
parameter.OleDbType = OleDbType.DBDate;
parameter.Value = DateTime.Now;
cmd.Parameters.Add(parameter);

No comments:

Post a Comment