C#对于数据库的增删查改

首先,放出主界面供大家观摩。
温馨提示,再进行增删查改之前需要手动建立数据库和数据表及对应字段。在注释当中,有很多知识点,可以停留一会好好消化。
在这里插入图片描述

功能1、向数据库中增加数据
在相应区域输入完毕后,点击“插入”按钮即可。

        private void button1_Click(object sender, EventArgs e)//增加
        {
            if (textBox1.Text=="" || textBox2.Text == "" || textBox3.Text == "" || textBox4.Text == "" || textBox5.Text == "")
            {
                MessageBox.Show("请输入完整的个人信息!");
            }
            else
            {
                string SQlstr = "server=UIM-AIR-II;Uid=sa;Pwd=fzj666,.;database =Information";
                SqlConnection con = new SqlConnection(SQlstr);//创建数据库连接对象
                con.Open();//打开连接

                string select = "select Snumber from db_Information where Snumber='"+textBox1.Text+"'";
                SqlCommand comm = new SqlCommand(select, con);
                SqlDataAdapter sd = new SqlDataAdapter(comm);
                DataSet ds = new DataSet();
                int n = sd.Fill(ds, "db_Information");
                if(n!=0)
                {
                    MessageBox.Show("该学号已存在!");
                }
                else
                {
                    string insert = "insert into db_Information(Snumber,Sclass,Sname,Ssex,Sage) values ('" + textBox1.Text + "','" + textBox2.Text + "','" + textBox3.Text + "','" + textBox4.Text + "','" + textBox5.Text + "')";
                    comm = new SqlCommand(insert, con);//Command对象对数据库进行增删查改

                    if (Convert.ToInt32(comm.ExecuteNonQuery()) > 0)//判断ExecuteNonQuery方法返回的参数是否大于0,大于0表示插入成功
                    {
                        MessageBox.Show("插入成功!");
                    }
                    else
                    {
                        MessageBox.Show("插入失败!");
                    }
                }
                con.Close();//关闭连接
            }
        }
            //Command对象常用的方法
            //ExecuteNonQuery   :常用于执行非select命令,比如insert、delete、update,并返回该命令所影响的行数,即该命令增加、删除、更改了多少行。
            //ExecuteScalar     :用于执行select命令,并返回数据中第一行第一列的值,常用于执行用到count或sum函数的select命令。
            //ExecuteReader     :执行select命令,并返回一个DataReader对象,该对象是一个只能向前读的数据集。

功能2、向数据库中删除数据
在学号那一栏输入学号,按“按学号删除”按钮即可

        private void button2_Click(object sender, EventArgs e)//删除
        {
            if (textBox1.Text == "")
            {
                MessageBox.Show("请输入被删除者的学号!");
            }
            else
            {
                string SQlstr = "server=UIM-AIR-II;Uid=sa;Pwd=fzj666,.;database =Information";
                SqlConnection con = new SqlConnection(SQlstr);//创建数据库连接对象
                con.Open();//打开连接

                string delete = "delete from db_Information where Snumber='" + textBox1.Text+"'";
                SqlCommand comm = new SqlCommand(delete, con);//Command对象对数据库进行增删查改

                if (Convert.ToInt32(comm.ExecuteNonQuery()) > 0)//判断ExecuteNonQuery方法返回的参数是否大于0,大于0表示删除成功
                {
                    MessageBox.Show("删除成功!");
                }
                else
                {
                    MessageBox.Show("删除失败!");
                }
                con.Close();//关闭连接
            }
        }

功能3、向数据库中查找数据
在学号那一栏输入学号,按“按学号查找”按钮即可

        private void button3_Click(object sender, EventArgs e)//查找
        {
            if (textBox1.Text == "")
            {
                MessageBox.Show("请输入被查找者的学号!");
            }
            else
            {
                string SQlstr = "server=UIM-AIR-II;Uid=sa;Pwd=fzj666,.;database =Information";
                SqlConnection con = new SqlConnection(SQlstr);//创建数据库连接对象
                con.Open();//打开连接

                string select = "select * from db_Information where Snumber='" + textBox1.Text + "'";
                SqlCommand comm = new SqlCommand(select, con);//Command对象对数据库进行增删查改          

                SqlDataReader sdr = comm.ExecuteReader();//SqlDataReader是一个对象集,用于从数据源中读取只读的数据。
                try
                {
                    if(sdr.HasRows)//判断数据库中是否有数据
                    {
                        sdr.Read();//跳到查询的数据集中的第一行
                        textBox1.Text = Convert.ToString(sdr["Snumber"]);//还可用下标代替,第1列的下标从0开始,以此类推
                        textBox2.Text = Convert.ToString(sdr["Sclass"]); //
                        textBox3.Text = Convert.ToString(sdr["Sname"]);  //
                        textBox4.Text = Convert.ToString(sdr["Ssex"]);   //
                        textBox5.Text = Convert.ToString(sdr["Sage"]);   //
                    }
                    MessageBox.Show("查询成功!");
                }
                catch(SqlException ex)
                {
                    MessageBox.Show(ex.ToString());
                }
                con.Close();//关闭连接
            }
        }
            //SqlDataReader对象的常用属性
            //HasRows:          判断数据库中是否有数据
            //FieldCount:        获取当前行的列数
            //RecordsAffected:   获取执行SQL语句所增、删、改的行数
            //Read:              令SqlDataReader对象前进到下一条记录
            //Get:               读取数据集当前行的某一列的数据
            //Close:             关闭SqlDataReader对象

功能4、向数据库中更改数据
在学号那一栏输入学号,在带有“新”标签的栏输入完整的且新的数据,按“按学号更改”按钮即可

        private void button4_Click(object sender, EventArgs e)//更改
        {
            if (textBox1.Text == "")
            {
                MessageBox.Show("请输入被更改者的旧学号!");
            }
            else if (textBox6.Text == "")
            {
                MessageBox.Show("请输入被更改者的新学号!");
            }
            else if (textBox7.Text == "" || textBox8.Text == "" || textBox9.Text == "" || textBox10.Text == "")
            {
                MessageBox.Show("请输入被更改者的新个人信息!");
            }
            else
            {
                string SQlstr = "server=UIM-AIR-II;Uid=sa;Pwd=fzj666,.;database =Information";
                SqlConnection con = new SqlConnection(SQlstr);//创建数据库连接对象
                con.Open();//打开连接

                string update = "update db_Information set Snumber='"+textBox6.Text+ "',Sclass='" + textBox7.Text + "',Sname='" + textBox8.Text + "',Ssex='" + textBox9.Text + "',Sage='" + textBox10.Text + "' where Snumber='" + textBox1.Text+"'";
                SqlCommand comm = new SqlCommand(update, con);//Command对象对数据库进行增删查改

                if (Convert.ToInt32(comm.ExecuteNonQuery()) > 0)//判断ExecuteNonQuery方法返回的参数是否大于0,大于0表示更改成功
                {
                    MessageBox.Show("更改成功!");
                }
                else
                {
                    MessageBox.Show("更改失败!");
                }
                
                con.Close();//关闭连接
            }
        }

功能5、读取该表中所有数据
按“读取内容”按钮即可

        private void button5_Click(object sender, EventArgs e)//读取
        {
            string SQlstr = "server=UIM-AIR-II;Uid=sa;Pwd=fzj666,.;database =Information";
            SqlConnection con = new SqlConnection(SQlstr);//创建数据库连接对象
            con.Open();//打开连接

            string duqu = "select * from db_Information";
            SqlCommand comm = new SqlCommand(duqu, con);//Command对象对数据库进行增删查改

            SqlDataReader sdr = comm.ExecuteReader();

            DataTable data = new DataTable();//法一显示在dataGridView1
            data.Load(sdr);
            dataGridView1.DataSource = data;

            //BindingSource bd = new BindingSource();//法二显示在dataGridView1
            //bd.DataSource = sdr;
            //dataGridView1.DataSource = bd;

            dataGridView1.Columns[0].HeaderText = "学号";
            dataGridView1.Columns[1].HeaderText = "班级";
            dataGridView1.Columns[2].HeaderText = "姓名";
            dataGridView1.Columns[3].HeaderText = "性别";
            dataGridView1.Columns[4].HeaderText = "年龄";
            //ColumnHeadersDefaultCellstyle可以将列标题设置为居中
        }

其他功能

        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)//显示
        {
            if (e.RowIndex>=0)
            {
                DataGridViewRow row = dataGridView1.Rows[e.RowIndex];
                textBox1.Text = row.Cells[0].Value.ToString();
                textBox2.Text = row.Cells[1].Value.ToString();
                textBox3.Text = row.Cells[2].Value.ToString();
                textBox4.Text = row.Cells[3].Value.ToString();
                textBox5.Text = row.Cells[4].Value.ToString();
            }
        }

        private void button6_Click(object sender, EventArgs e)//清除内容
        {
            textBox1.Text = ""; textBox6.Text  = "";
            textBox2.Text = ""; textBox7.Text  = "";
            textBox3.Text = ""; textBox8.Text  = "";
            textBox4.Text = ""; textBox9.Text  = "";
            textBox5.Text = ""; textBox10.Text = "";
        }

        private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            e.CellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            //将DataGridView单元格里面的内容设置为居中
        }

最后,附上源码,如有不懂欢迎咨询。

using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;

namespace 数据库的增删改查
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)//增加
        {
            if (textBox1.Text=="" || textBox2.Text == "" || textBox3.Text == "" || textBox4.Text == "" || textBox5.Text == "")
            {
                MessageBox.Show("请输入完整的个人信息!");
            }
            else
            {
                string SQlstr = "server=UIM-AIR-II;Uid=sa;Pwd=fzj666,.;database =Information";
                SqlConnection con = new SqlConnection(SQlstr);//创建数据库连接对象
                con.Open();//打开连接

                string select = "select Snumber from db_Information where Snumber='"+textBox1.Text+"'";
                SqlCommand comm = new SqlCommand(select, con);
                SqlDataAdapter sd = new SqlDataAdapter(comm);
                DataSet ds = new DataSet();
                int n = sd.Fill(ds, "db_Information");
                if(n!=0)
                {
                    MessageBox.Show("该学号已存在!");
                }
                else
                {
                    string insert = "insert into db_Information(Snumber,Sclass,Sname,Ssex,Sage) values ('" + textBox1.Text + "','" + textBox2.Text + "','" + textBox3.Text + "','" + textBox4.Text + "','" + textBox5.Text + "')";
                    comm = new SqlCommand(insert, con);//Command对象对数据库进行增删查改

                    //Command对象常用的方法
                    //ExecuteNonQuery   :常用于执行非select命令,比如insert、delete、update,并返回该命令所影响的行数,即该命令增加、删除、更改了多少行。
                    //ExecuteScalar     :用于执行select命令,并返回数据中第一行第一列的值,常用于执行用到count或sum函数的select命令。
                    //ExecuteReader     :执行select命令,并返回一个DataReader对象,该对象是一个只能向前读的数据集。

                    if (Convert.ToInt32(comm.ExecuteNonQuery()) > 0)//判断ExecuteNonQuery方法返回的参数是否大于0,大于0表示插入成功
                    {
                        MessageBox.Show("插入成功!");
                    }
                    else
                    {
                        MessageBox.Show("插入失败!");
                    }
                }
                con.Close();//关闭连接
            }
        }

        private void button2_Click(object sender, EventArgs e)//删除
        {
            if (textBox1.Text == "")
            {
                MessageBox.Show("请输入被删除者的学号!");
            }
            else
            {
                string SQlstr = "server=UIM-AIR-II;Uid=sa;Pwd=fzj666,.;database =Information";
                SqlConnection con = new SqlConnection(SQlstr);//创建数据库连接对象
                con.Open();//打开连接

                string delete = "delete from db_Information where Snumber='" + textBox1.Text+"'";
                SqlCommand comm = new SqlCommand(delete, con);//Command对象对数据库进行增删查改

                if (Convert.ToInt32(comm.ExecuteNonQuery()) > 0)//判断ExecuteNonQuery方法返回的参数是否大于0,大于0表示删除成功
                {
                    MessageBox.Show("删除成功!");
                }
                else
                {
                    MessageBox.Show("删除失败!");
                }
                con.Close();//关闭连接
            }
        }

        private void button3_Click(object sender, EventArgs e)//查找
        {
            if (textBox1.Text == "")
            {
                MessageBox.Show("请输入被查找者的学号!");
            }
            else
            {
                string SQlstr = "server=UIM-AIR-II;Uid=sa;Pwd=fzj666,.;database =Information";
                SqlConnection con = new SqlConnection(SQlstr);//创建数据库连接对象
                con.Open();//打开连接

                string select = "select * from db_Information where Snumber='" + textBox1.Text + "'";
                SqlCommand comm = new SqlCommand(select, con);//Command对象对数据库进行增删查改          

                //SqlDataReader对象的常用属性
                //HasRows:          判断数据库中是否有数据
                //FieldCount:        获取当前行的列数
                //RecordsAffected:   获取执行SQL语句所增、删、改的行数
                //Read:              令SqlDataReader对象前进到下一条记录
                //Get:               读取数据集当前行的某一列的数据
                //Close:             关闭SqlDataReader对象

                SqlDataReader sdr = comm.ExecuteReader();//SqlDataReader是一个对象集,用于从数据源中读取只读的数据。
                try
                {
                    if(sdr.HasRows)//判断数据库中是否有数据
                    {
                        sdr.Read();//跳到查询的数据集中的第一行
                        textBox1.Text = Convert.ToString(sdr["Snumber"]);//还可用下标代替,第1列的下标从0开始,以此类推
                        textBox2.Text = Convert.ToString(sdr["Sclass"]); //
                        textBox3.Text = Convert.ToString(sdr["Sname"]);  //
                        textBox4.Text = Convert.ToString(sdr["Ssex"]);   //
                        textBox5.Text = Convert.ToString(sdr["Sage"]);   //
                        MessageBox.Show("查询成功!");
                    }
                    else
                    {
                        MessageBox.Show("查询失败!");
                    }
                    
                }
                catch(SqlException ex)
                {
                    MessageBox.Show(ex.ToString());
                }

                con.Close();//关闭连接
            }
        }

        private void button4_Click(object sender, EventArgs e)//更改
        {
            if (textBox1.Text == "")
            {
                MessageBox.Show("请输入被更改者的旧学号!");
            }
            else if (textBox6.Text == "")
            {
                MessageBox.Show("请输入被更改者的新学号!");
            }
            else if (textBox7.Text == "" || textBox8.Text == "" || textBox9.Text == "" || textBox10.Text == "")
            {
                MessageBox.Show("请输入被更改者的新个人信息!");
            }
            else
            {
                string SQlstr = "server=UIM-AIR-II;Uid=sa;Pwd=fzj666,.;database =Information";
                SqlConnection con = new SqlConnection(SQlstr);//创建数据库连接对象
                con.Open();//打开连接

                string update = "update db_Information set Snumber='"+textBox6.Text+ "',Sclass='" + textBox7.Text + "',Sname='" + textBox8.Text + "',Ssex='" + textBox9.Text + "',Sage='" + textBox10.Text + "' where Snumber='" + textBox1.Text+"'";
                SqlCommand comm = new SqlCommand(update, con);//Command对象对数据库进行增删查改

                if (Convert.ToInt32(comm.ExecuteNonQuery()) > 0)//判断ExecuteNonQuery方法返回的参数是否大于0,大于0表示更改成功
                {
                    MessageBox.Show("更改成功!");
                }
                else
                {
                    MessageBox.Show("更改失败!");
                }
                
                con.Close();//关闭连接
            }
        }

        private void button5_Click(object sender, EventArgs e)//读取内容
        {
            string SQlstr = "server=UIM-AIR-II;Uid=sa;Pwd=fzj666,.;database =Information";
            SqlConnection con = new SqlConnection(SQlstr);//创建数据库连接对象
            con.Open();//打开连接

            string duqu = "select * from db_Information";
            SqlCommand comm = new SqlCommand(duqu, con);//Command对象对数据库进行增删查改

            SqlDataReader sdr = comm.ExecuteReader();

            DataTable data = new DataTable();//法一显示在dataGridView1
            data.Load(sdr);
            dataGridView1.DataSource = data;

            //BindingSource bd = new BindingSource();//法二显示在dataGridView1
            //bd.DataSource = sdr;
            //dataGridView1.DataSource = bd;

            dataGridView1.Columns[0].HeaderText = "学号";
            dataGridView1.Columns[1].HeaderText = "班级";
            dataGridView1.Columns[2].HeaderText = "姓名";
            dataGridView1.Columns[3].HeaderText = "性别";
            dataGridView1.Columns[4].HeaderText = "年龄";
            //ColumnHeadersDefaultCellstyle可以将列标题设置为居中
        }

        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)//显示
        {
            if (e.RowIndex>=0)
            {
                DataGridViewRow row = dataGridView1.Rows[e.RowIndex];
                textBox1.Text = row.Cells[0].Value.ToString();
                textBox2.Text = row.Cells[1].Value.ToString();
                textBox3.Text = row.Cells[2].Value.ToString();
                textBox4.Text = row.Cells[3].Value.ToString();
                textBox5.Text = row.Cells[4].Value.ToString();
            }
        }

        private void button6_Click(object sender, EventArgs e)//清除内容
        {
            textBox1.Text = ""; textBox6.Text  = "";
            textBox2.Text = ""; textBox7.Text  = "";
            textBox3.Text = ""; textBox8.Text  = "";
            textBox4.Text = ""; textBox9.Text  = "";
            textBox5.Text = ""; textBox10.Text = "";
        }

        private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            e.CellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            //将DataGridView单元格里面的内容设置为居中
        }
    }
}
  • 39
    点赞
  • 232
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 18
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 18
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

孤独的根号三号程序员

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值