protected void Button3_Click(object sender, EventArgs e)
    {
        GridView1.Visible = true;
        string str = ConfigurationManager.AppSettings["connectionStrings"].ToString();
        SqlConnection con = new SqlConnection(str);
        con.Open();
        string sqlIns = "insert into Mat  (Mno,Mname,Matt,Muse) values ('" + TextBox1.Text + "','" + TextBox2.Text + "','" + TextBox3.Text + "','" + TextBox4.Text + "')";
        SqlCommand com = new SqlCommand(sqlIns, con);
        if (com.ExecuteNonQuery() > 0)
        {            Response.Write("<script>alert('添加成功!')</script>");        }
        else
        {
            Response.Write("<script>alert('用户已存在,请重新输入!')</script>");
        }
        this.oo();
    }

解决方案 »

  1.   

    第一种方法,先查询是否存在
    第二种直接try finally。但第二种如果存在其它错误则直接不报错
    protected void Button3_Click(object sender, EventArgs e)
      {
      GridView1.Visible = true;
      string str = ConfigurationManager.AppSettings["connectionStrings"].ToString();
      SqlConnection con = new SqlConnection(str);
      con.Open();
      string sqlIns = "insert into Mat (Mno,Mname,Matt,Muse) values ('" + TextBox1.Text + "','" + TextBox2.Text + "','" + TextBox3.Text + "','" + TextBox4.Text + "')";
      SqlCommand com = new SqlCommand(sqlIns, con);
      try
      {
      if (com.ExecuteNonQuery() > 0)
      {  Response.Write("<script>alert('添加成功!')</script>");  }
      else
      {
      Response.Write("<script>alert('用户已存在,请重新输入!')</script>");
      }
      this.oo();
      }
      finally
      {
         con.close();
       }
      }
      

  2.   

    数据库里工号设成自动增长,就不要inSert 工号了
      

  3.   

    如果是主健的吧,插入相同值,数据库会自动阻止吧消息 2627,级别 14,状态 1,第 1 行
    违反了 PRIMARY KEY 约束 'PK_bbs'。不能在对象 'dbo.bbs' 中插入重复键。
    语句已终止。