首页 > 数据库 >学生管理系统-WinForm(C#)与MySQL

学生管理系统-WinForm(C#)与MySQL

时间:2022-12-22 13:24:13浏览次数:46  
标签:sName string C# sNo msop private MySQL new WinForm

一、创建数据库

1 创建数据库

create database studentmanagersystem;

2 创建表login和student

CREATE TABLE login(
	user VARCHAR(50) PRIMARY KEY,
	passwd VARCHAR(50) NOT NULL
)

CREATE TABLE student(
	sNo VARCHAR(50) PRIMARY KEY,
	sName VARCHAR(50) NOT NULL,
	age INT NOT NULL,
	sex VARCHAR(50) NOT NULL,
	score INT NOT NULL
)

3 增加数据

INSERT INTO login VALUES('admin','123');

INSERT INTO student VALUES('1','张三',20,'男',98);
INSERT INTO student VALUES('2','李艳',19,'女',85);

*4 数据操作

# 修改数据
UPDATE student SET sName='李燕' WHERE sNo=2;
# 删除数据
DELETE FROM student WHERE sNo=2;
# 查询
SELECT sNo,sName,age,sex,score FROM student;

二、创建WinForm项目

1 设计界面

1.1 登录界面

 

 

 

使用控件:2个label控件,2个textbox控件(分别取名:tbName和tbPasswd),1个button控件(btnLogin)

1.2 管理界面

 

 

 

使用控件:1个DataGridView(dgvShow),1个TextBox(tbByName),5个button(btnAdd、btnDeleted、btnUpdate、btnSort与btnQuery)

1.3 信息输入界面

 

 

 

使用控件:5个Label、5个TextBox(tbSno、tbSname、tbSex、tbAge、tbScore),1个button(btnSave)

2 创建类(与数据库对应)

目的:便于 按学生对象的方式查询

internal class StudentInfo {
    public string sNo { get; set; }
    public string sName { get; set; }
    public string sex { get; set; }
    public int age { get; set; }
    public int score { get; set; }

    public StudentInfo(string sNo, string sName, string sex, int age, int score) {
        this.sNo = sNo ?? throw new ArgumentNullException(nameof(sNo));
        this.sName = sName ?? throw new ArgumentNullException(nameof(sName));
        this.sex = sex ?? throw new ArgumentNullException(nameof(sex));
        this.age = age;
        this.score = score;
    }

    public override string ToString() {
        return $"学生信息:学号:{this.sNo},姓名:{this.sName}," +
            $"性别:{this.sex},年龄:{this.age},得分:{this.score}";
    }
}

3 连接MySQL数据库

 

 

 

具体操作:

(1)下载 MySql.Data.dll

一般在MySQL安装器内,有.NET相关的。

(2)引用 MySql.Data.dll

在Visual Studio的“解决方案资源管理器”里 ,选择“引用”,右键“添加引用”,添加对应版本的MySql.Data.dll动态库文件。

那么如何找到?找到对应.NET版本(选择项目,右键属性,查看目标框架)文件路径的 MySql.Data.dll动态库。

例如:本人项目的版本是 .net framework 4.8  对应路径:C:\Program Files (x86)\MySQL\Connector NET 8.0\Assemblies\v4.8\MySql.Data.dll

(3)连接MySQL数据库

创建连接字符串——>MySqlConnection对象——>MySQLCommand对象

 

为了代码组织更方便,这里我也创建了一个数据库操作类(MySqlOpHelper),方便操作数据库。

internal class MySqlOpHelper {
    private string conStr = null;
    private MySqlConnection msc = null;
    private MySqlCommand msco = null;
    private MySqlDataReader msdr= null;
    // 用于系统登录 存储用户名和密码
    public Dictionary<string, string> dics = null;
    // 用于数据库查询后的数据对象List<StudentInfo>
    public List<StudentInfo> stus = null;         

    public MySqlOpHelper(string conStr) {
        this.conStr = conStr ?? throw new ArgumentNullException(nameof(conStr));
    }

    /// <summary>
    /// 系统 登录
    /// </summary>
    /// <param name="opStr"></param>
    public void OpLoginMySql(string queryStr) {
        try {
            msc = new MySqlConnection(conStr);
            msc.Open();
            msco = new MySqlCommand(queryStr, this.msc);
            msdr = msco.ExecuteReader();
            dics = new Dictionary<string, string>();
            while (msdr.Read()) {
                dics.Add(msdr[0].ToString(), msdr[1].ToString());
            }
        } catch {
            MessageBox.Show("登录失败!", "用户登录", MessageBoxButtons.OK, MessageBoxIcon.Error);
        } finally {
            msco.Dispose();
            msc.Close();
        }
    }

    /// <summary>
    /// 数据库操作 增删改
    /// </summary>
    /// <param name="opStr"></param>
    public void OpAddDeleUpdateMySql(string opStr) { 
        try {
            msc = new MySqlConnection(conStr);
            msco = new MySqlCommand(opStr,this.msc);
            msc.Open();
            msco.ExecuteNonQuery();
            MessageBox.Show("操作成功!", "数据库操作", MessageBoxButtons.OK, MessageBoxIcon.Information);
        } catch {
            MessageBox.Show("操作失败!", "数据库操作", MessageBoxButtons.OK, MessageBoxIcon.Error);
        } finally { 
            msco.Dispose();
            msc.Close();
        }
    }

    /// <summary>
    /// 数据库操作 查询
    /// </summary>
    /// <param name="queryStr"></param>
    public void OpQueryMySql(string queryStr) {
        try {
            msc = new MySqlConnection(conStr);
            msco = new MySqlCommand(queryStr, this.msc);
            msc.Open();
            msdr = msco.ExecuteReader();
            stus = new List<StudentInfo>();
            while (msdr.Read()) {
                stus.Add(new StudentInfo(msdr[0].ToString(), msdr[1].ToString(), msdr[2].ToString(),
                    int.Parse(msdr[3].ToString()), int.Parse(msdr[4].ToString())));
            }
            //foreach(var i in stus) {
            //    MessageBox.Show(i.ToString());
            //}
        } catch {
            MessageBox.Show("查询失败!", "数据库查询", MessageBoxButtons.OK, MessageBoxIcon.Error);
        } finally {
            msco.Dispose();
            msc.Close();
        }
    }
}

4 登录功能实现

/// <summary>
/// 数据库连接字符串
/// </summary>
private string connectStr = "server=127.0.0.1;port=3306;user=root;password=1234;database=studentmanagersystem";
/// <summary>
/// 数据库login表查询语句,用户登录
/// </summary>
private string operatorStr = "select name,passwd from login;";

/// <summary>
/// 登录 事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnLogin_Click(object sender, EventArgs e) {
    LoginSystem();
}

/// <summary>
/// 登录方法
/// </summary>
private void LoginSystem() {
    MySqlOpHelper msoph = new MySqlOpHelper(connectStr);
    msoph.OpLoginMySql(operatorStr);
    bool flag = false;
    foreach (var i in msoph.dics) {
        if (tbName.Text == i.Key && tbPasswd.Text == i.Value) {
            flag = true;
            new stumanager().Show();
            this.Hide();
        }
    }
    if (flag == false) {
        MessageBox.Show("登录失败!", "用户登录", MessageBoxButtons.OK, MessageBoxIcon.Warning);
    }
}

5 学生管理功能实现

5.1 增、删、改

(1)增 操作

// 信息输入窗口 类
/// <summary>
/// 数据库连接字符串
/// </summary>
private string connectStr = "server=127.0.0.1;port=3306;user=root;password=1234;database=studentmanagersystem";

/// <summary>
/// 信息保存 事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnSave_Click(object sender, EventArgs e) {
    string addStr = $"insert into student(sNo,sName,sex,age,score) values('{tbSno.Text}','{tbSname.Text}'," +
        $"'{tbSex.Text}',{int.Parse(tbAge.Text)},{int.Parse(tbScore.Text)});";
    MySqlOpHelper msop=new MySqlOpHelper(connectStr);
    msop.OpAddDeleUpdateMySql(addStr);
    tbSno.Text = "";
    tbSname.Text = "";
    tbSex.Text = "";
    tbAge.Text = "";
    tbScore.Text = "";
}

// 管理界面——事件
/// <summary>
/// 增 事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnAdd_Click(object sender, EventArgs e) {
    new studentinput().Show();
}

(2)删 操作

/// <summary>
/// 删 事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnDeleted_Click(object sender, EventArgs e) {
    DeleteData();
}

/// <summary>
/// 删除方法
/// </summary>
private void DeleteData() {
    // 获取选中的学生
    StudentInfo currentStu = msop.stus[dgvShow.CurrentRow.Index];
    //MessageBox.Show(currentStu.sNo);
    string deleteStr = $"delete from student where sNo='{currentStu.sNo}';";
    msop = new MySqlOpHelper(connectStr);
    msop.OpAddDeleUpdateMySql(deleteStr);
}

(3)改 操作

/// <summary>
/// 修改 事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnUpdate_Click(object sender, EventArgs e) {
    UpdateData();
}

/// <summary>
/// 修改方法
/// </summary>
private void UpdateData() {
    StudentInfo selectedStu = msop.stus[dgvShow.CurrentRow.Index];
    string updateStr = $"update student set sName='{dgvShow["sName", dgvShow.CurrentRow.Index].Value}'," +
        $"sex='{dgvShow["sex", dgvShow.CurrentRow.Index].Value}'," +
        $"age={dgvShow["age", dgvShow.CurrentRow.Index].Value}," +
        $"score={dgvShow["score", dgvShow.CurrentRow.Index].Value} where sNo='{selectedStu.sNo}'";
    msop = new MySqlOpHelper(connectStr);
    msop.OpAddDeleUpdateMySql(updateStr);
}

5.2 查

/// <summary>
/// 数据库连接字符串
/// </summary>
private string connectStr = "server=127.0.0.1;port=3306;user=root;password=1234;database=studentmanagersystem";
/// <summary>
/// 数据库student表查询语句
/// </summary>
private string operatorStr = "select sNo,sName,sex,age,score from student;";
/// <summary>
/// 用于各种数据操作 自定义类
/// </summary>
MySqlOpHelper msop = null;

/// <summary>
/// 显示数据
/// </summary>
private void ShowStudentInfo() {
    msop = new MySqlOpHelper(connectStr);
    // 获得msop.stus 这个对象集合 List<StudentInfo>
    msop.OpQueryMySql(operatorStr);
    // 数据源绑定
    dgvShow.DataSource = msop.stus;
}

/// <summary>
/// 查询 事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnQuery_Click(object sender, EventArgs e) {
    // 直接查询
    if (tbByName.Text == "") {
        ShowStudentInfo();
    } else {
        // 通过姓名查找
        operatorStr = $"select sNo,sName,sex,age,score from student where sName='{tbByName.Text}';";
        ShowStudentInfo();
        operatorStr = "select sNo,sName,sex,age,score from student";
    }
}

5.3 排序

/// <summary>
/// 按成绩排序 事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnSort_Click(object sender, EventArgs e) {
    if (msop != null) {
        msop.OpQueryMySql(operatorStr);
        msop.stus.Sort(delegate (StudentInfo stu1, StudentInfo stu2) {
            return stu2.score.CompareTo(stu1.score);
        });
        dgvShow.DataSource = msop.stus;// 排序后,数据源重写绑定
    } else {
        MessageBox.Show("排序失败!", "数据排序", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}

 

源代码下载地址:https://github.com/WANN-A/StudentManagerSystem.git

 

标签:sName,string,C#,sNo,msop,private,MySQL,new,WinForm
From: https://www.cnblogs.com/swbna/p/16998325.html

相关文章