C#与数据库2——练习增删改查

  1. 数据库建立
    建立TestSchool数据库并在此数据库下建立表格TblClassId
    C#与数据库2——练习增删改查_第1张图片

  2. 建立Windows窗体应用Form1
    C#与数据库2——练习增删改查_第2张图片

  3. 创建TblClassIdl类,用以绑定数据

public class TblClassId//创建类
    {
        //Id,Name,Desc
        public int Id { get; set; }//属性
        //public int Id;//改成字段的话在绑定数据的时候就不显示了
        public string Name { get; set; }
        //public string Name;
        public string Desc { get; set; }
        //public string Desc;
        //public string 我的属性
        //{
        //    get { return "测试"; }
            
        //}

        
    }
  1. 主窗体程序
//窗体加载事件
        private void Form1_Load(object sender, EventArgs e)
        {
            //将TblClassId表中的数据读取到一个List
            LoadData();
        }

        private void LoadData()
        {
            List<TblClassId> list = new List<TblClassId>();//创建集合

            string constr = @"server=DESKTOP-FAVDBP3\MSSQLSERVER2014;user=123;pwd=123;database=TestSchool";
            SqlConnection con = new SqlConnection(constr);
            string sql = "select * from TblClassId";
            SqlCommand cmd = new SqlCommand(sql,con);
            con.Open();
            SqlDataReader reader = cmd.ExecuteReader();
            //判断是否查询到了数据
            if (reader.HasRows)
            {
                //一条一条读取数据
                while (reader.Read())
                {
                    //Id,Name,Desc
                    TblClassId model = new TblClassId();
                    model.Id = reader.GetInt32(0);
                    model.Name = reader.GetString(1);
                    model.Desc = reader.IsDBNull(2) ? null : reader.GetString(2);//处理空值

                    //数据绑定需要注意的一点:
                    //数据绑定的时候。只认“属性”,不认“字段”。
                    //数据绑定是通过反射来实现的,反射只反射里面的属性,不反射里面的字段
                    list.Add(model);//把model对象加入到list集合里面
                }
                
            }
            this.dgvClassId.DataSource = list;//数据绑定
            con.Close();
        }

        //增加一条数据
        private void button1_Click(object sender, EventArgs e)
        {
            //1.采集用户输入
            string cName = CName.Text.Trim();
            string cDesc = CDesc.Text.Trim();

            //2.执行插入操作
            string constr = @"server=DESKTOP-FAVDBP3\MSSQLSERVER2014;user=123;pwd=123;database=TestSchool";
            SqlConnection con = new SqlConnection(constr);
            string sql = string.Format("insert into TblClassId values('{0}','{1}')", cName, cDesc);
            //string sql = string.Format("insert into TblClassId output inserted.Id values('{0}','{1}')", cName, cDesc);
            SqlCommand cmd = new SqlCommand(sql, con);
            con.Open();
            int r = cmd.ExecuteNonQuery();
            if (r > 0)
            {
                //MessageBox.Show("插入成功!");//会阻塞进程
                this.Text = "插入成功!";
                LoadData();//重新加载DataGridVie控件
            }
            else
            {
                //MessageBox.Show("插入了" + r + "行。!");
                this.Text = "插入了" + r + "行。!";
            }
            con.Close();


            //object obj = cmd.ExecuteScalar();
            //this.Text = "刚刚插入记录的自动编号是:" + obj.ToString();
            //LoadData();

        }

        //行获取焦点事件
        private void dgvClassId_RowEnter(object sender, DataGridViewCellEventArgs e)
        {
            //获取当前选中的行对象
            DataGridViewRow currentRow = this.dgvClassId.Rows[e.RowIndex];

            //获取当前行中绑定的TblClassId数据对象
            TblClassId model = currentRow.DataBoundItem as TblClassId;
            if(model!=null)
            {
                CId.Text = model.Id.ToString();
                EditName.Text = model.Name;
                EditDesc.Text = model.Desc;
            }
        }

        //保存修改数据
        private void button2_Click(object sender, EventArgs e)
        {
            //1.采集用户输入
            TblClassId model = new TblClassId();
            model.Id = Convert.ToInt32(CId.Text);
            model.Name =EditName.Text.Trim();
            model.Desc =EditDesc.Text.Trim();

            //2.连接数据库,执行操作
            string constr = @"server=DESKTOP-FAVDBP3\MSSQLSERVER2014;user=123;pwd=123;database=TestSchool";
            SqlConnection con = new SqlConnection(constr);
            string sql = string.Format("update TblClassId set Name='{0}',[Desc]='{1}' where Id={2}",
                model.Name,model.Desc,model.Id);
            SqlCommand cmd = new SqlCommand(sql, con);
            con.Open();
            int r = cmd.ExecuteNonQuery();
            this.Text = "更新了" + r + "行。";

            LoadData();//重新加载,绑定DataGridView,使里面的数据能够更新
            con.Close();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            DialogResult result= MessageBox.Show("确定要删除吗?", "操作提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
            if(result==System.Windows.Forms.DialogResult.OK)
            {
                int Id = Convert.ToInt32(CId.Text);
                string constr = @"server=DESKTOP-FAVDBP3\MSSQLSERVER2014;user=123;pwd=123;database=TestSchool";
                SqlConnection con = new SqlConnection(constr);
                string sql = string.Format("delete from TblClassId where Id={0}", Id);
                SqlCommand cmd = new SqlCommand(sql, con);
                con.Open();
                int r = cmd.ExecuteNonQuery();
                this.Text = "删除了" + r + "条数据。";
                LoadData();
                con.Close();
            }
        }
  1. 调试

你可能感兴趣的:(SQL,c#,数据结构,算法)