我想在页面上点击一个按钮时候数据库表里添加数据,不过不知道怎么写了。按钮事件里怎么调用SQL语句的方法!哪位高手帮帮!!最好写一段简单程序!!

解决方案 »

  1.   

     protected void Button1_Click(object sender, EventArgs e)
            {
                string constring="Data Source=.;Initial Catalog=数据库名;Integrated Security=True";
                using (SqlConnection con = new SqlConnection(constring))
               {            con.Open();
                string sql = "insert into 表名(列) values(1)";
                SqlCommand cmd = new SqlCommand(sql, con);
                int intStr = cmd.ExecuteNonQuery();
                if (intStr > 0)
                {
                    Response.Write("插入成功");
                }
                else 
                {
                    Response.Write("失败");
                }
            }            }
                else 
                {
                    Response.Write("失败");
                }
      

  2.   

    楼上ok,不过注意try catch捕获异常
      

  3.   

    try
                    {
                        con.Open();
                        SqlCommand cmd = new SqlCommand("Select * FROM 表名", con);
                        SqlDataAdapter sda = new SqlDataAdapter();
                        sda.SelectCommand = cmd;
                        ds = new DataSet();
                        dt = new DataTable();
                        sda.Fill(ds);                    dt = ds.Tables[0];
                        if(ds.Tables[0].Rows.Count>0)
                         {
                               Messagebox.Show("成功");
                         } 
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("报错原因:" + ex.Message);
                        return;
                    }
      

  4.   

    以上代码写在botton的单击事件里面
      

  5.   


    在这个基础上加上try{}catch{}就行了,你懂的
      

  6.   

     string constring="Data Source=.;Initial Catalog=数据库名;Integrated Security=True";
      using (SqlConnection con = new SqlConnection(constring))                   con.Open();
                        SqlCommand cmd = new SqlCommand("Select * FROM 表名", con);
                        SqlDataAdapter sda = new SqlDataAdapter();
                        sda.SelectCommand = cmd;
                        ds = new DataSet();
                        dt = new DataTable();
                        sda.Fill(ds);打包放着也行  这杨每次用都要写