ADO.NET更新数据

更新数据唯一不同的地方是Sql语句,将更新代码添加到“更新”按钮的Click事件。代码如下:

        private void btnModify_Click(object sender, EventArgs e)
        {
            string strcon = @"data source=.\sqlexpress;initial catalog=School;uid=sa;pwd=123456";
            SqlConnection con = new SqlConnection(strcon);
            string sql = "update Student set sname='"+this.txtName.Text+"',ssex='"+this.cboSex.Text+"',sage='"+Convert.ToInt32(this.txtAge.Text)+"',sclass='"+this.cboClass.Text+"' where id="+Convert.ToInt32(this.txtId.Text)+"";
            SqlCommand comm = new SqlCommand(sql, con);
            try
            {
                con.Open();
                if (comm.ExecuteNonQuery() > 0)
                {
                    MessageBox.Show("更新成功");

                }
                else
                {
                    MessageBox.Show("更新失败");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);

            }
            finally
            {
                con.Close();

            }
        }

注意:Sql语言编写时应区分单引号与双引号的引用,字符串和数字的表达方式。

posted on 2012-07-12 10:00  流星落  阅读(227)  评论(0编辑  收藏  举报

导航