【完结撒花】基于Windows C# 桌面窗体应用(.NET framework) 程序的Access学生数据库管理系统(三)---数据管理系统页面之SQL增删改查

前言


0 准备工作

0-1 进入系统
  • 我们回到上一节编写的LoginForm.cs,为登录成功的用户添加进行系统的代码
 if (count > 0)
 {
     MessageBox.Show("登录成功!");
     StudentsDataSetCheckerForm studentdatabases_form= new StudentsDataSetCheckerForm();
     studentdatabases_form.ShowDialog();
 }
0-2 系统数据库共享
  • 考虑到整个StudentsDataSetCheckerForm.cs都将用到StudentsDataBaseConnector实例和连接,这里我们就将其设置为类内全局的私有变量
   private OleDbConnection connection; 
  public StudentsDataSetCheckerForm()
  {
      InitializeComponent();
      cbxGender.Items.AddRange(new string[] { "男", "女" });
      cbxClass.Items.AddRange(new string[] { "1班", "2班", "3班", "4班" });
      cbxMajor.Items.AddRange(new string[] { "计算机科学", "自动化", "车辆工程", "测控" });
      StudentsDataBaseConnector studentsDataBaseConnector = StudentsDataBaseConnector.GetInstance();
      connection = studentsDataBaseConnector.GetStudentDataBaseConnection();
    
  }
0-3 数据库关闭
  • StudentsDataSetCheckerForm.cs中,我们进行以下判断保证获取连接时正确的
   public OleDbConnection GetStudentDataBaseConnection()
   {
       try
       {
           if (connection.State != ConnectionState.Open)
           {
               connection.Open();
           }
           
       }
       catch (Exception ex)
       {
           MessageBox.Show(ex.Message);
           if (connection.State == ConnectionState.Open)
           {
               connection.Close();
           }
       }
       return connection;
   }
0-4 数据库创建
  • 上一节我们讲过了,这一块我们迅速完成请添加图片描述

  • 注意这里电话是短文本类型


请添加图片描述


1 显示全部----数据库全遍历

  • 我们来完成显示全部的逻辑,代码很简单
private void btnDisplayAll_Click(object sender, EventArgs e)
{
    
    string query = "SELECT 学号, 姓名, 性别, 出生日期, 地址, 班级, 专业, 联系方式 FROM StudentDataBase1";
    OleDbDataAdapter adapter = new OleDbDataAdapter(query, connection);
    DataTable dataTable = new DataTable();
    adapter.Fill(dataTable);
    dataGridView1.DataSource = dataTable;
}

请添加图片描述


2 搜索

2-1 清空输出
  • 我们写几个清空函数,分别用于清空输出和清空数据显示
  • dataGridView1.DataSource = null;通过指定数据源为空来清空网格输出
private void ClearAllInput()
{
    tbxID.Clear();
    tbxName.Clear();
    tbxAdress.Clear();  
    tbxTel.Clear();
    cbxGender.Items.Clear();
    cbxClass.Items.Clear();
    cbxMajor.Items.Clear();
}
private void ClearDataGridView()
{
    dataGridView1.DataSource = null;
}
2-2 判断输入合法
  • cbxMajor.SelectedIndex == -1表示下拉选项没有人选
  • !int.TryParse(tbxID.Text, out _)也是表示是否为数字
  • @"^\d{10}$"正则表达式,用于匹配恰好10位数字的电话号码
 private bool isAllInputInValid()
 {
     if(string.IsNullOrEmpty(tbxID.Text)&& 
         string.IsNullOrEmpty(tbxName.Text)&&
         string.IsNullOrEmpty(tbxTel.Text)&&
             string.IsNullOrEmpty(tbxAdress.Text)&&
             cbxMajor.SelectedIndex == -1&&
             cbxGender.SelectedIndex == -1 &&
             cbxClass.SelectedIndex == -1 
             )
     {
         MessageBox.Show("你必须填一项!");
         ClearAllInput();
         ClearDataGridView();
         return false;
     }
     if (!string.IsNullOrEmpty(tbxID.Text)&&!int.TryParse(tbxID.Text, out _))
     {
         MessageBox.Show("学号必须是数字");
         ClearAllInput();
         ClearDataGridView();
         return false; 
     }

     // 正则表达式,用于匹配恰好10位数字的电话号码
     string pattern = @"^\d{10}$";
     if (!string.IsNullOrEmpty(tbxTel.Text) && !Regex.IsMatch(tbxTel.Text, pattern))
     {
         MessageBox.Show("电话号码必须是10位数字");
         ClearAllInput();
         ClearDataGridView();
         return false;
     }
     return true;
 }
2-3 获取用户选择的字段
  • 我们写一个函数,用于判断用户填了哪些字段,然后进行构建查询条件
private List<string> BuildSearchConditions()
{
    List<string> conditions = new List<string>();
    if (!string.IsNullOrEmpty(tbxID.Text))
    {
        conditions.Add("学号 = " + tbxID.Text);
    }
    if (!string.IsNullOrEmpty(tbxName.Text))
    {
        conditions.Add("姓名 = '" + tbxName.Text + "'");
    }
    if (cbxGender.SelectedIndex != -1)
    {
        conditions.Add("性别 = '" + cbxGender.SelectedItem.ToString() + "'");
    }
    if (!string.IsNullOrEmpty(tbxTel.Text))
    {
        conditions.Add("联系方式 = '" + tbxTel.Text + "'");
    }
    if (!string.IsNullOrEmpty(tbxAdress.Text))
    {
        conditions.Add("地址 = '" + tbxAdress.Text + "'");
    }
    if (cbxClass.SelectedIndex != -1)
    {
        conditions.Add("班级 = '" + cbxClass.SelectedItem.ToString() + "'");
    }
    if (cbxMajor.SelectedIndex != -1)
    {
        conditions.Add("专业 = '" + cbxMajor.SelectedItem.ToString() + "'");
    }
    return conditions;
}
2-4 进行查找
  • 在上述两个函数的帮助下,我们能很快进行查找请添加图片描述
 private void btnSearch_Click(object sender, EventArgs e)
 {
     ClearDataGridView();
     if (!isAllInputInValid())
     {
         ClearAllInput();
         return;
     }
     string query = "SELECT * FROM StudentDataBase1 WHERE ";

     // 构建查询条件
     List<string> conditions = BuildSearchConditions();

     // 如果没有条件,则不执行查询
     if (conditions.Count == 0)
     {
         MessageBox.Show("请至少选择一个搜索条件");
         return;
     }

     query += string.Join(" AND ", conditions);
     MessageBox.Show("SQL:" + query);
     OleDbDataAdapter adapter = new OleDbDataAdapter(query, connection);
     DataTable dataTable = new DataTable();
     adapter.Fill(dataTable);
     dataGridView1.DataSource = dataTable;
 }

3 添加—数据库添加

  • 添加一条全新的数据我们需要确保用户完成了全部内容的编写,我们写一个函数来判断
    private bool isAllFeildFilled()
    {
        if (!string.IsNullOrEmpty(tbxID.Text) &&
            !string.IsNullOrEmpty(tbxName.Text) &&
            !string.IsNullOrEmpty(tbxTel.Text) &&
                !string.IsNullOrEmpty(tbxAdress.Text) &&
                cbxMajor.SelectedIndex != -1 &&
                cbxGender.SelectedIndex != -1 &&
                cbxClass.SelectedIndex != -1
                )
        {  return true; }
        MessageBox.Show("请确认所有信息都填写完成!");
        return false;
    }

请添加图片描述

  • 剩下的就简单了,添加只需要确保学号唯一,进行添加即可,如果学号已经存在,提示用户
private void btnAdd_Click(object sender, EventArgs e)
{
    ClearDataGridView();
    if (!isAllInputInValid())
    {
        ClearAllInput();
        ClearDataGridView();
        return;
    }
    if (!isAllFeildFilled())
    {
        ClearAllInput();
        ClearDataGridView();
        return;
    }

    // 检查学号是否已存在
    string checkIDQuery = "SELECT COUNT(*) FROM StudentDataBase1 WHERE 学号 = @StudentID";
    OleDbCommand checkIDCommand = new OleDbCommand(checkIDQuery, connection);
    checkIDCommand.Parameters.AddWithValue("@StudentID", tbxID.Text);

    // 执行查询
    int count = (int)checkIDCommand.ExecuteScalar();

    if (count > 0)
    {
        MessageBox.Show("该学号已存在,请输入不同的学号。");
        ClearAllInput();
        ClearDataGridView();
        return;
    }

    // 学号不存在,可以继续添加记录
    string addRecordQuery = "INSERT INTO StudentDataBase1 (学号, 姓名, 性别, 出生日期, 地址, 班级, 专业, 联系方式) VALUES (@StudentID, @Name, @Gender, @BirthDate, @Address, @Class, @Major, @Phone)";
    OleDbCommand addRecordCommand = new OleDbCommand(addRecordQuery, connection);
    addRecordCommand.Parameters.AddWithValue("@StudentID", tbxID.Text);
    addRecordCommand.Parameters.AddWithValue("@Name", tbxName.Text);
    addRecordCommand.Parameters.AddWithValue("@Gender", cbxGender.SelectedItem.ToString());
    addRecordCommand.Parameters.AddWithValue("@BirthDate", dtpBirth.Value.Date); 
    addRecordCommand.Parameters.AddWithValue("@Address", tbxAdress.Text);
    addRecordCommand.Parameters.AddWithValue("@Class", cbxClass.SelectedItem.ToString());
    addRecordCommand.Parameters.AddWithValue("@Major", cbxMajor.SelectedItem.ToString());
    addRecordCommand.Parameters.AddWithValue("@Phone", tbxTel.Text);

    // 执行插入操作
    int rowsAffected = addRecordCommand.ExecuteNonQuery();

    if (rowsAffected > 0)
    {
        MessageBox.Show("记录添加成功!");
        ClearAllInput();
        ClearDataGridView();
    }
    else
    {
        MessageBox.Show("记录添加失败!");
        ClearDataGridView();
    }
}
  • 当学号出现冲突时请添加图片描述

  • 正常运行请添加图片描述

  • 数据被正常添加请添加图片描述


4 修改—数据库修改

  • 修改操作,我们需要确认用户是否进行查找,我们判断出现的查找框是否为空来判断 dataGridView1.Rows.Count == 0
  • 同理我们写一个辅助函数用户添加内容
   private void AddParametersToUpdateCommand(OleDbCommand updateCommand)
   {
       if (!string.IsNullOrEmpty(tbxID.Text))
       {
           updateCommand.Parameters.AddWithValue("@StudentID", tbxID.Text);
       }
       if (!string.IsNullOrEmpty(tbxName.Text))
       {
           updateCommand.Parameters.AddWithValue("@Name", tbxName.Text);
       }
       if (cbxGender.SelectedIndex != -1)
       {
           updateCommand.Parameters.AddWithValue("@Gender", cbxGender.SelectedItem.ToString());
       }
       if (!string.IsNullOrEmpty(tbxTel.Text))
       {
           updateCommand.Parameters.AddWithValue("@Phone", tbxTel.Text);
       }
       if (!string.IsNullOrEmpty(tbxAdress.Text))
       {
           updateCommand.Parameters.AddWithValue("@Address", tbxAdress.Text);
       }
       if (cbxClass.SelectedIndex != -1)
       {
           updateCommand.Parameters.AddWithValue("@Class", cbxClass.SelectedItem.ToString());
       }
       if (cbxMajor.SelectedIndex != -1)
       {
           updateCommand.Parameters.AddWithValue("@Major", cbxMajor.SelectedItem.ToString());
       }
   }
  • 然后我们完成逻辑
   private void btnEditor_Click(object sender, EventArgs e)
   {
       // 检查dataGridView1中是否有数据
       if (dataGridView1.DataSource == null || dataGridView1.Rows.Count == 0)
       {
           MessageBox.Show("请先进行查找操作。");
           ClearAllInput();
           ClearDataGridView();
           return;
       }
       
       if (!isAllInputInValid())
       {
           ClearAllInput();
           ClearDataGridView();
           return;
       }

       // 获取dataGridView1中的当前记录
       DataGridViewRow selectedRow = dataGridView1.CurrentRow;
       string studentID = selectedRow.Cells["学号"].Value.ToString();

       // 构建更新查询
       string updateQuery = "UPDATE StudentDataBase1 SET ";
       List<string> updateConditions = BuildSearchConditions();

       // 如果没有更新条件,则不执行更新
       if (updateConditions.Count == 0)
       {
           MessageBox.Show("请至少选择一个更新字段");
           ClearAllInput();
           ClearDataGridView();
           return;
       }

       updateQuery += string.Join(", ", updateConditions);
       updateQuery += " WHERE 学号 = @StudentID";

       OleDbCommand updateCommand = new OleDbCommand(updateQuery, connection);
       updateCommand.Parameters.AddWithValue("@StudentID", studentID);

       AddParametersToUpdateCommand(updateCommand);

       // 提示用户即将进行的更改
       MessageBox.Show("即将更新记录:" + updateQuery, "确认更新", MessageBoxButtons.OK, MessageBoxIcon.Information);

       // 弹出确认对话框
       DialogResult result = MessageBox.Show("你确定要更新这些记录吗?", "确认更新", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
       if (result == DialogResult.No)
       {
           return; // 用户选择取消
       }

       // 执行更新操作
       int rowsAffected = updateCommand.ExecuteNonQuery();

       if (rowsAffected > 0)
       {
           MessageBox.Show("记录更新成功!");
           ClearAllInput();
           ClearDataGridView();
       }
       else
       {
           MessageBox.Show("更新失败。");
       }
   }
  • 尝试修改请添加图片描述

  • 修改成功请添加图片描述

  • 当有多条记录的时候进行选择可以更新指定数据请添加图片描述


5 删除—数据库删除

  • 数据的删除和搜索逻辑类似,判断用户输入的字段请添加图片描述
 private void btnDelete_Click(object sender, EventArgs e)
 {
     
     if (!isAllInputInValid())
     {
         ClearAllInput();
         ClearDataGridView();
         return;
     }

     string selectQuery = "SELECT * FROM StudentDataBase1 WHERE ";

     // 构建查询条件
     List<string> conditions = BuildSearchConditions();

     // 如果没有条件,则不执行查询
     if (conditions.Count == 0)
     {
         MessageBox.Show("请至少选择一个删除条件");
         ClearAllInput();
         ClearDataGridView();
         return;
     }

     selectQuery += string.Join(" AND ", conditions);
     OleDbDataAdapter adapter = new OleDbDataAdapter(selectQuery, connection);
     DataTable dataTable = new DataTable();
     adapter.Fill(dataTable);

     // 检查是否有记录符合条件
     if (dataTable.Rows.Count == 0)
     {
         MessageBox.Show("没有找到匹配的记录。");
         ClearAllInput();
         ClearDataGridView();
         return;
     }

     // 显示符合条件的记录
     dataGridView1.DataSource = dataTable;

     // 弹出确认对话框
     DialogResult result = MessageBox.Show("你确定要删除这些记录吗?", "确认删除", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
     if (result == DialogResult.No)
     {
         return; // 用户选择取消
     }

     // 执行删除操作
     string deleteQuery = "DELETE FROM StudentDataBase1 WHERE " + string.Join(" AND ", conditions);
     OleDbCommand deleteCommand = new OleDbCommand(deleteQuery, connection);
     int rowsAffected = deleteCommand.ExecuteNonQuery();

     if (rowsAffected > 0)
     {
         MessageBox.Show("记录删除成功!");
         ClearAllInput();
         ClearDataGridView();
     }
     else
     {
         MessageBox.Show("删除失败。");
     }
 }

6 退出

  • 这个没什么,秒了
 private void btnExit_Click(object sender, EventArgs e)
 {
     DialogResult result = MessageBox.Show("你确定要退出吗?", "确认退出", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
     if (result == DialogResult.Yes)
     {
         this.Close(); 
     }
 }

请添加图片描述


7 完整代码

  • 完结撒花
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace StudentDatasetsExplorer
{
    public partial class StudentsDataSetCheckerForm : Form
    {

        private void ClearAllInput()
        {
            tbxID.Clear();
            tbxName.Clear();
            tbxAdress.Clear();  
            tbxTel.Clear();
            cbxGender.SelectedIndex = -1;
            cbxClass.SelectedIndex = -1;
            cbxMajor.SelectedIndex = -1;
        }
        private void ClearDataGridView()
        {
            dataGridView1.DataSource = null;
        }
        private bool isAllInputInValid()
        {
            if(string.IsNullOrEmpty(tbxID.Text)&& 
                string.IsNullOrEmpty(tbxName.Text)&&
                string.IsNullOrEmpty(tbxTel.Text)&&
                    string.IsNullOrEmpty(tbxAdress.Text)&&
                    cbxMajor.SelectedIndex == -1&&
                    cbxGender.SelectedIndex == -1 &&
                    cbxClass.SelectedIndex == -1 
                    )
            {
                MessageBox.Show("你必须填一项!");
                ClearAllInput();
                ClearDataGridView();
                return false;
            }
            if (!string.IsNullOrEmpty(tbxID.Text)&&!int.TryParse(tbxID.Text, out _))
            {
                MessageBox.Show("学号必须是数字");
                ClearAllInput();
                ClearDataGridView();
                return false; 
            }

            // 正则表达式,用于匹配恰好10位数字的电话号码
            string pattern = @"^\d{10}$";
            if (!string.IsNullOrEmpty(tbxTel.Text) && !Regex.IsMatch(tbxTel.Text, pattern))
            {
                MessageBox.Show("电话号码必须是10位数字");
                ClearAllInput();
                ClearDataGridView();
                return false;
            }
            return true;
        }
        private OleDbConnection connection; 
        public StudentsDataSetCheckerForm()
        {
            InitializeComponent();
            cbxGender.Items.AddRange(new string[] { "男", "女" });
            cbxClass.Items.AddRange(new string[] { "1班", "2班", "3班", "4班" });
            cbxMajor.Items.AddRange(new string[] { "计算机科学", "自动化", "车辆工程", "测控" });
            StudentsDataBaseConnector studentsDataBaseConnector = StudentsDataBaseConnector.GetInstance();
            connection = studentsDataBaseConnector.GetStudentDataBaseConnection();
          
        }

        private void btnDisplayAll_Click(object sender, EventArgs e)
        {
            
            string query = "SELECT 学号, 姓名, 性别, 出生日期, 地址, 班级, 专业, 联系方式 FROM StudentDataBase1";

           
            OleDbDataAdapter adapter = new OleDbDataAdapter(query, connection);

            DataTable dataTable = new DataTable();

           
            adapter.Fill(dataTable);

           
            dataGridView1.DataSource = dataTable;
        }
        
        private List<string> BuildSearchConditions()
        {
            List<string> conditions = new List<string>();
            if (!string.IsNullOrEmpty(tbxID.Text))
            {
                conditions.Add("学号 = " + tbxID.Text);
            }
            if (!string.IsNullOrEmpty(tbxName.Text))
            {
                conditions.Add("姓名 = '" + tbxName.Text + "'");
            }
            if (cbxGender.SelectedIndex != -1)
            {
                conditions.Add("性别 = '" + cbxGender.SelectedItem.ToString() + "'");
            }
            if (!string.IsNullOrEmpty(tbxTel.Text))
            {
                conditions.Add("联系方式 = '" + tbxTel.Text + "'");
            }
            if (!string.IsNullOrEmpty(tbxAdress.Text))
            {
                conditions.Add("地址 = '" + tbxAdress.Text + "'");
            }
            if (cbxClass.SelectedIndex != -1)
            {
                conditions.Add("班级 = '" + cbxClass.SelectedItem.ToString() + "'");
            }
            if (cbxMajor.SelectedIndex != -1)
            {
                conditions.Add("专业 = '" + cbxMajor.SelectedItem.ToString() + "'");
            }
         
            return conditions;
        }
        private void btnSearch_Click(object sender, EventArgs e)
        {
            ClearDataGridView();
            if (!isAllInputInValid())
            {
                ClearAllInput();
                return;
            }
            string query = "SELECT * FROM StudentDataBase1 WHERE ";

            // 构建查询条件
            List<string> conditions = BuildSearchConditions();

            // 如果没有条件,则不执行查询
            if (conditions.Count == 0)
            {
                MessageBox.Show("请至少选择一个搜索条件");
                return;
            }

            query += string.Join(" AND ", conditions);
            MessageBox.Show("SQL:" + query);
            OleDbDataAdapter adapter = new OleDbDataAdapter(query, connection);
            DataTable dataTable = new DataTable();
            adapter.Fill(dataTable);
            dataGridView1.DataSource = dataTable;


        }
        private bool isAllFeildFilled()
        {
            if (!string.IsNullOrEmpty(tbxID.Text) &&
                !string.IsNullOrEmpty(tbxName.Text) &&
                !string.IsNullOrEmpty(tbxTel.Text) &&
                    !string.IsNullOrEmpty(tbxAdress.Text) &&
                    cbxMajor.SelectedIndex != -1 &&
                    cbxGender.SelectedIndex != -1 &&
                    cbxClass.SelectedIndex != -1
                    )
            {  return true; }
            MessageBox.Show("请确认所有信息都填写完成!");
            return false;
        }
        private void btnAdd_Click(object sender, EventArgs e)
        {
            ClearDataGridView();
            if (!isAllInputInValid())
            {
                ClearAllInput();
                ClearDataGridView();
                return;
            }
            if (!isAllFeildFilled())
            {
                ClearAllInput();
                ClearDataGridView();
                return;
            }

            // 检查学号是否已存在
            string checkIDQuery = "SELECT COUNT(*) FROM StudentDataBase1 WHERE 学号 = @StudentID";
            OleDbCommand checkIDCommand = new OleDbCommand(checkIDQuery, connection);
            checkIDCommand.Parameters.AddWithValue("@StudentID", tbxID.Text);

            // 执行查询
            int count = (int)checkIDCommand.ExecuteScalar();

            if (count > 0)
            {
                MessageBox.Show("该学号已存在,请输入不同的学号。");
                ClearAllInput();
                ClearDataGridView();
                return;
            }

            // 学号不存在,可以继续添加记录
            string addRecordQuery = "INSERT INTO StudentDataBase1 (学号, 姓名, 性别, 出生日期, 地址, 班级, 专业, 联系方式) VALUES (@StudentID, @Name, @Gender, @BirthDate, @Address, @Class, @Major, @Phone)";
            OleDbCommand addRecordCommand = new OleDbCommand(addRecordQuery, connection);
            addRecordCommand.Parameters.AddWithValue("@StudentID", tbxID.Text);
            addRecordCommand.Parameters.AddWithValue("@Name", tbxName.Text);
            addRecordCommand.Parameters.AddWithValue("@Gender", cbxGender.SelectedItem.ToString());
            addRecordCommand.Parameters.AddWithValue("@BirthDate", dtpBirth.Value.Date); 
            addRecordCommand.Parameters.AddWithValue("@Address", tbxAdress.Text);
            addRecordCommand.Parameters.AddWithValue("@Class", cbxClass.SelectedItem.ToString());
            addRecordCommand.Parameters.AddWithValue("@Major", cbxMajor.SelectedItem.ToString());
            addRecordCommand.Parameters.AddWithValue("@Phone", tbxTel.Text);

            // 执行插入操作
            int rowsAffected = addRecordCommand.ExecuteNonQuery();

            if (rowsAffected > 0)
            {
                MessageBox.Show("记录添加成功!");
                ClearAllInput();
                ClearDataGridView();
            }
            else
            {
                MessageBox.Show("记录添加失败!");
                ClearDataGridView();
            }
        }

        private void AddParametersToUpdateCommand(OleDbCommand updateCommand)
        {
            if (!string.IsNullOrEmpty(tbxID.Text))
            {
                updateCommand.Parameters.AddWithValue("@StudentID", tbxID.Text);
            }
            if (!string.IsNullOrEmpty(tbxName.Text))
            {
                updateCommand.Parameters.AddWithValue("@Name", tbxName.Text);
            }
            if (cbxGender.SelectedIndex != -1)
            {
                updateCommand.Parameters.AddWithValue("@Gender", cbxGender.SelectedItem.ToString());
            }
            if (!string.IsNullOrEmpty(tbxTel.Text))
            {
                updateCommand.Parameters.AddWithValue("@Phone", tbxTel.Text);
            }
            if (!string.IsNullOrEmpty(tbxAdress.Text))
            {
                updateCommand.Parameters.AddWithValue("@Address", tbxAdress.Text);
            }
            if (cbxClass.SelectedIndex != -1)
            {
                updateCommand.Parameters.AddWithValue("@Class", cbxClass.SelectedItem.ToString());
            }
            if (cbxMajor.SelectedIndex != -1)
            {
                updateCommand.Parameters.AddWithValue("@Major", cbxMajor.SelectedItem.ToString());
            }

        }
        private void btnEditor_Click(object sender, EventArgs e)
        {
            // 检查dataGridView1中是否有数据
            if (dataGridView1.DataSource == null || dataGridView1.Rows.Count == 0)
            {
                MessageBox.Show("请先进行查找操作。");
                ClearAllInput();
                ClearDataGridView();
                return;
            }
            
            if (!isAllInputInValid())
            {
                ClearAllInput();
                ClearDataGridView();
                return;
            }

            // 获取dataGridView1中的当前记录
            DataGridViewRow selectedRow = dataGridView1.CurrentRow;
            string studentID = selectedRow.Cells["学号"].Value.ToString();

            // 构建更新查询
            string updateQuery = "UPDATE StudentDataBase1 SET ";
            List<string> updateConditions = BuildSearchConditions();

            // 如果没有更新条件,则不执行更新
            if (updateConditions.Count == 0)
            {
                MessageBox.Show("请至少选择一个更新字段");
                ClearAllInput();
                ClearDataGridView();
                return;
            }

            updateQuery += string.Join(", ", updateConditions);
            updateQuery += " WHERE 学号 = @StudentID";

            OleDbCommand updateCommand = new OleDbCommand(updateQuery, connection);
            updateCommand.Parameters.AddWithValue("@StudentID", studentID);

            AddParametersToUpdateCommand(updateCommand);

            // 提示用户即将进行的更改
            MessageBox.Show("即将更新记录:" + updateQuery, "确认更新", MessageBoxButtons.OK, MessageBoxIcon.Information);

            // 弹出确认对话框
            DialogResult result = MessageBox.Show("你确定要更新这些记录吗?", "确认更新", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
            if (result == DialogResult.No)
            {
                return; // 用户选择取消
            }

            // 执行更新操作
            int rowsAffected = updateCommand.ExecuteNonQuery();

            if (rowsAffected > 0)
            {
                MessageBox.Show("记录更新成功!");
                ClearAllInput();
                ClearDataGridView();
            }
            else
            {
                MessageBox.Show("更新失败。");
            }
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
           
            if (!isAllInputInValid())
            {
                ClearAllInput();
                ClearDataGridView();
                return;
            }

            string selectQuery = "SELECT * FROM StudentDataBase1 WHERE ";

            // 构建查询条件
            List<string> conditions = BuildSearchConditions();

            // 如果没有条件,则不执行查询
            if (conditions.Count == 0)
            {
                MessageBox.Show("请至少选择一个删除条件");
                ClearAllInput();
                ClearDataGridView();
                return;
            }

            selectQuery += string.Join(" AND ", conditions);
            OleDbDataAdapter adapter = new OleDbDataAdapter(selectQuery, connection);
            DataTable dataTable = new DataTable();
            adapter.Fill(dataTable);

            // 检查是否有记录符合条件
            if (dataTable.Rows.Count == 0)
            {
                MessageBox.Show("没有找到匹配的记录。");
                ClearAllInput();
                ClearDataGridView();
                return;
            }

            // 显示符合条件的记录
            dataGridView1.DataSource = dataTable;

            // 弹出确认对话框
            DialogResult result = MessageBox.Show("你确定要删除这些记录吗?", "确认删除", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
            if (result == DialogResult.No)
            {
                return; // 用户选择取消
            }

            // 执行删除操作
            string deleteQuery = "DELETE FROM StudentDataBase1 WHERE " + string.Join(" AND ", conditions);
            OleDbCommand deleteCommand = new OleDbCommand(deleteQuery, connection);
            int rowsAffected = deleteCommand.ExecuteNonQuery();

            if (rowsAffected > 0)
            {
                MessageBox.Show("记录删除成功!");
                ClearAllInput();
                ClearDataGridView();
            }
            else
            {
                MessageBox.Show("删除失败。");
            }
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            DialogResult result = MessageBox.Show("你确定要退出吗?", "确认退出", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
            if (result == DialogResult.Yes)
            {
                this.Close(); 
            }
        }
    }
}


8 总结-完结撒花

  • 到此这个系列就完结撒花了
  • 我们通过Windows C#的桌面应用程序来做一个学生数据库查询系统,其中学生数据库的信息是存储在Access数据库的.accdb文件中,并且我们我们通过SQL实现了对数据库的增删改查
  • 希望此教程对大家有帮助,如有错误,欢迎指出!!!
  • 14
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值