ASP.NET C# 向 ACCESS 插入日期型数据 标准表明式中数据类型不包容

 

public static string connstring = “Provider=Microsoft.Jet.OLEDB.4.0;Data
Source=” +
        System.Web.HttpContext.Current.Server.MapPath(“db.mdb”);   

public int addMsg(string name, string sex, string web, string email,
string words, string ip, string come, string qq)
    {//重回影响操作的行数–增多
        try
        {

//string sqlIns = “insert into 表名(name,nowDate)
values(‘helloworld’,#” + DateTime.Now.ToLocalTime() +”#)”
//注意表名和列名不可能为主要字:如date,time等

            string QueryString = “insert into
words(name,sex,web,email,words,Createdate,ip,come,qq)
values(@name,@sex,@web,@email,@words,@Createdate,@ip,@come,@qq)”;
            OleDbConnection conn = new OleDbConnection(connstring);
            conn.Open();
            OleDbCommand cmd = new OleDbCommand(QueryString, conn);
            cmd.Parameters.AddWithValue(“@name”, name);
            cmd.Parameters.AddWithValue(“@sex”, sex);
            cmd.Parameters.AddWithValue(“@web”, web);
            cmd.Parameters.AddWithValue(“@email”, email);
            cmd.Parameters.AddWithValue(“@words”, words);
          

          //cmd.Parameters.AddWithValue(“@Createdate”,
DateTime.Now.ToLocalTime());

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

            cmd.Parameters.AddWithValue(“@ip”, ip);
            cmd.Parameters.AddWithValue(“@come”, come);
            cmd.Parameters.AddWithValue(“@qq”, qq);
            return cmd.ExecuteNonQuery();
        }
        catch
        {
            return 0;
        }
        finally
        {
            conn.Close();
            conn.Dispose();
        }
    }

PS:

在向Access数据库中添增添少的时候,假如是日期字段,则会现出“标准表达式中数据类型不包容。”的不当,那可能是C#中的日期类型不能直接调换到Access中的日期类型奥莱DbType.DBDate所致.

如下:

//cmd.Parameters.AddWithValue(“@Createdate”, time);

解决办法正是将地方语句中的 cmd.Parameters.AddWithValue(“@CreateDate”,
DateTime.Now); 转变来上面包车型地铁言语就能够:

化解办法正是将方面语句中的 cmd.Parameters.AddWithValue(“@Createdate”,
DateTime.Now.ToLocalTime());转变来下边包车型客车言语就可以:

if (commandParameters[i].Value is DateTime)
                    {
                        OleDbParameter parameter = new
OleDbParameter();
                        parameter.ParameterName =
commandParameters[i].ParameterName;
                        parameter.OleDbType = OleDbType.DBDate;
                        parameter.Value =
commandParameters[i].Value;
                        cmd.Parameters.Add(parameter);
                    }
                    else
                    {
                       
cmd.Parameters.AddWithValue(commandParameters[i].ParameterName,
commandParameters[i].Value);
                        cmd.Parameters[i].Direction =
commandParameters[i].Direction;
                    }

相关文章