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

    多思考,多创新,才是正道!
  • 相关阅读:
    Uva11584 Partitioning by Palindromes
    GYM100741 A Queries
    Uva11400 Lighting System Design
    UVA12563 Jin Ge Jin Qu hao
    Uva116 Unidirectional TSP
    HDU2089 不要62
    BZOJ3670: [Noi2014]动物园
    Uva11384 Help is needed for Dexter
    Uva1347 Tour
    BZOJ1924: [Sdoi2010]所驼门王的宝藏
  • 原文地址:https://www.cnblogs.com/shuang121/p/1969336.html
Copyright © 2020-2023  润新知