日期:2014-05-18  浏览次数:20439 次

command插入数据总是出问题
想用command插入数据,但是总是出问题,数据根本就没进入数据库啊,不知道什么问题,在page_load 中加入了if(!ispostback) 了,插入的按钮代码如下,不知哪里出了问题啊
  protected void sendmsg_Click(object sender, EventArgs e)
  { 
  string strconn = WebConfigurationManager.ConnectionStrings["istudyconn"].ConnectionString;
  SqlConnection conn = new SqlConnection(strconn);
  string sqlcomm = "insert into msginfo (senduser,recuser,msgcontent,readflag) values (@senduser,@recuser,@msgcontent,0)";
  SqlCommand comm = new SqlCommand(sqlcomm,conn);
  comm.Parameters.Add("@senduser", SqlDbType.NVarChar, 50);
  comm.Parameters.Add("@recuser", SqlDbType.NVarChar, 50);
  comm.Parameters.Add("@msgcontent", SqlDbType.Text);
  comm.Parameters["@senduser"].Value = Session["user"].ToString();
  comm.Parameters["@recuser"].Value = Request.QueryString["jieshou"];
  comm.Parameters["@msgcontent"].Value = msgbox.Text;
  conn.Open();
  comm.ExecuteNonQuery();
  conn.Close();
  }

------解决方案--------------------

C# code

 protected void sendmsg_Click(object sender, EventArgs e)
  {  
  string strconn = WebConfigurationManager.ConnectionStrings["istudyconn"].ConnectionString;
  SqlConnection conn = new SqlConnection(strconn);
  conn.Open();
  string sqlcomm = "insert into msginfo (senduser,recuser,msgcontent,readflag) values (@senduser,@recuser,@msgcontent,0)";
  SqlCommand comm = new SqlCommand(sqlcomm,conn);
  SqlParameter[] sp = new SqlParameter[]
  {
       new SqlParameter("@senduser",SqlDbType.NVarChar,50),
       new SqlParameter("@recuser",SqlDbType.NVarChar,50),
       new SqlParameter("@msgcontent",SqlDbType.Text),                            
  };
  sp[0].Value = Session["user"].ToString();
  sp[1].Value = Request.QueryString["jieshou"];
  sp[2].Value = msgbox.Text;
  com.Parameters.AddRange(sp);    
  comm.ExecuteNonQuery();
  comm.Dispose();
  conn.Dispose();
  conn.Close();
  }