日期:2014-05-17  浏览次数:20712 次

cmd.ExecuteNonQuery();运行时报错
各位高手,cmd.ExecuteNonQuery();运行时报错,报错内容为:不允许数据类型从datetime到int的隐式转换。请使用CONVERT函数来运行此查询。我是在做一个新闻系统,现向数据库中插入一条新的新闻,插入的项有:标题,内容,时间,发送人,点击率。操作类中的代码如下:using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

/// <summary>
/// Operate 的摘要说明
/// </summary>
public class Operate
{
public Operate()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
  public string title;
  public string newscontent;
  public string sort; 
  public int hits;
  public DateTime sendtime;
  public string sender;

  public static bool insert(Operate p)
  {
  SqlConnection con = DB.createCon();
  con.Open();
  SqlCommand cmd = new SqlCommand("insert into newsdetails values(@title,@newscontent,@sort,@sendtime,@sender,@hits)", con);
  SqlParameter para1 = new SqlParameter("title", SqlDbType.VarChar, 50);
  para1.Value = p.title;
  cmd.Parameters.Add(para1);
  SqlParameter para2 = new SqlParameter("newscontent", SqlDbType.VarChar, 200);
  para2.Value = p.newscontent;
  cmd.Parameters.Add(para2);
  SqlParameter para3 = new SqlParameter("sort", SqlDbType.VarChar, 50);
  para3.Value = p.sort;
  cmd.Parameters.Add(para3);
  SqlParameter para4 = new SqlParameter("sendtime", SqlDbType.DateTime);
  para4.Value = p.sendtime;
  cmd.Parameters.Add(para4);
  SqlParameter para5 = new SqlParameter("sender", SqlDbType.VarChar, 20);
  para5.Value = p.sender;
  cmd.Parameters.Add(para5);
  SqlParameter para6 = new SqlParameter("hits", SqlDbType.Int);
  para6.Value = p.hits;
  cmd.Parameters.Add(para6);
  cmd.ExecuteNonQuery();
  return true;

  }
}

.cs文件中的代码如下:
  protected void dijiao_Click(object sender, EventArgs e)
  {
  if (Page.IsValid)
  {
  Operate p = new Operate();
  p.title = this.txttitle.Text;
  p.newscontent = this.txtcontent.Text;
  p.sort = this.ddlsort.SelectedValue.ToString();
  p.sendtime =DateTime.Now;
  p.sender = Session["adminName"].ToString();
  if (Operate.insert(p))
  {
  Response.Write("<script language=javascript>alert('添加新闻成功!')</script>");
  }

  }

  }

------解决方案--------------------
尝试完整的写出insert语句:
"insert into newsdetails([title],newscontent,[sort],sendtime,sender,hits) values(@title,@newscontent,@sort,@sendtime,@sender,@hits)"

或者在参数SqlParameter中指定参数对应的字段...