protected void btnSend_Click(object sender, EventArgs e)
    {
        if (ddlIfName.SelectedIndex == 0)
        {
            //建立与数据库的连接
            SqlConnection con = new SqlConnection("server=(local);user id=sa; pwd=;database=聊天室数据库");
            con.Open();
            //创建SqlCommand命令执行查询结果
            SqlCommand com = new SqlCommand("select count(*) from tb_user where Name='" + Label4.Text + "'", con);
            int count = Convert.ToInt32(com.ExecuteScalar());
            if (count > 0)
            {
                //调用ExecCommand方法执行SQL插入命令
                mc.ExecCommand("insert into tb_matter (Id,Name,IP,Matter,infoTime) values('" + Label4.Text + "','" + Label4.Text + "','" + Session["IP"] + "','" + Label4.Text + "说:" + txtSpeak.Text + "','"+ DateTime.Now  +"')");3
                 Label5.Text = txtSpeak.Text;
                 txtSpeak.Text = "syy" ;
            }
        }
   }
当第一次点击btnSend(button)时,可移执调用ExecCommand方法执行SQL插入命令,把txtSpeak.Text插入到数据库中, 但是第二次点击btnSend(button)时, Label5.Text 会变化,但是东西没有插入数据库,为什么?

解决方案 »

  1.   

    mc.ExecCommand方法内部实现可能有问题。
      

  2.   

    public bool ExecCommand(string sqlstr)
        {
            //创建数据库连接
            SqlConnection con = new SqlConnection("Data Source=(local);User ID=sa;PWD=;DataBase=db_ManyChat");
            //打开数据库连接
            con.Open();
            //创建SqlCommand对象的实例
            SqlCommand com = new SqlCommand(sqlstr, con);
            try
            {
                //执行Sql语句命令
                com.ExecuteNonQuery();
                return true;
            }
            catch
            {
                return false;
            }
            finally
            {
                //关闭数据库连接
                con.Close();
            }
        }
      

  3.   

    public bool ExecCommand(string sqlstr)
      {
      //创建数据库连接
      SqlConnection con = new SqlConnection("Data Source=(local);User ID=sa;PWD=;DataBase=db_ManyChat");
      //打开数据库连接
      con.Open();
      //创建SqlCommand对象的实例
      SqlCommand com = new SqlCommand(sqlstr, con);
      try
      {
      //执行Sql语句命令
      com.ExecuteNonQuery();
      return true;
      }
      catch
      {
      return false;
      }
      finally
      {
      //关闭数据库连接
      con.Close();
      }
      }