数据库实验:学生管理系统 C# / VS

学生信息管理系统

开发工具:Microsoft SQL Serever 2014/Microsoft Visual studio 2019
开发语言:SQL/C#
主要功能:
系统用户由管理员和学生组成。
通过注册获得登录权力,通过密钥找回密码。
管理员功能:管理学生信息、课程信息、分数(增加、删除、修改),读取已注册的所有账户的信息(密码加密不可见)。
学生功能:更改个人基本信息,管理个人课程(选课、退课),查询个人分数,注销个人账号。
数据库实验:学生管理系统 C# / VS_第1张图片
在SQL serever中新建数据库,新建表,添加数据

--建数据库
CREATE DATABASE QIAO;
--建表Student
CREATE TABLE Student
(	 
Sno CHAR(9) PRIMARY KEY,  
Sname CHAR(20) UNIQUE, 
Ssex CHAR(2), 
Sage SMALLINT,
Sdept CHAR(20) 
); 
--建表Course 
CREATE TABLE  Course 
(	 
Cno CHAR(4) PRIMARY KEY,
Cname CHAR(40),             
Cpno CHAR(4),               	                       
Ccredit SMALLINT,
FOREIGN KEY (Cpno) REFERENCES  Course(Cno)
);
--建表SC 
CREATE TABLE  SC 
( 
Sno CHAR(9),  
Cno CHAR(4),  
Grade SMALLINT, 
PRIMARY KEY (Sno,Cno), 
FOREIGN KEY (Sno) REFERENCES Student(Sno),
FOREIGN KEY (Cno)REFERENCES Course(Cno)
);  
--建表ID
CREATE TABLE ID
(	 
Name NCHAR(20) PRIMARY KEY,  
password NCHAR(32), 
Answer NCHAR(11), 
Birthday DATETIME,
userIdentity NCHAR(20),
userPhoto image,
Question NCHAR(20)  
); 
--插入数据
INSERT  INTO  Student (Sno,Sname,Ssex,Sdept,Sage) VALUES ('201215121','李勇','男','CS',20);
INSERT  INTO  Student (Sno,Sname,Ssex,Sdept,Sage) VALUES ('201215122','刘晨','女','CS',19);
INSERT  INTO  Student (Sno,Sname,Ssex,Sdept,Sage) VALUES ('201215123','王敏','女','MA',18);
INSERT  INTO  Student (Sno,Sname,Ssex,Sdept,Sage) VALUES ('201215125','张立','男','IS',19);
INSERT  INTO  Student (Sno,Sname,Ssex,Sdept,Sage) VALUES ('201215128','陈冬','男','IS',20); 

INSERT  INTO Course(Cno,Cname,Cpno,Ccredit)	VALUES ('1','数据库',NULL,4);
INSERT  INTO Course(Cno,Cname,Cpno,Ccredit)	VALUES ('2','数学',NULL,4);
INSERT  INTO Course(Cno,Cname,Cpno,Ccredit)	VALUES ('3','信息系统',NULL,4);
INSERT  INTO Course(Cno,Cname,Cpno,Ccredit)	VALUES ('4','操作系统',NULL,4);
INSERT  INTO Course(Cno,Cname,Cpno,Ccredit)	VALUES ('5','数据结构',NULL,4);
INSERT  INTO Course(Cno,Cname,Cpno,Ccredit)	VALUES ('6','数据处理',NULL,4);
INSERT  INTO Course(Cno,Cname,Cpno,Ccredit)	VALUES ('7','Pascal语言',NULL,4); 

UPDATE Course SET Cpno = '5' WHERE Cno = '1'
UPDATE Course SET Cpno = '1' WHERE Cno = '3' 
UPDATE Course SET Cpno = '6' WHERE Cno = '4' 
UPDATE Course SET Cpno = '7' WHERE Cno = '5' 
UPDATE Course SET Cpno = '6' WHERE Cno = '7'  

INSERT  INTO SC(Sno,Cno,Grade) VALUES ('201215121 ','1',92);
INSERT  INTO SC(Sno,Cno,Grade) VALUES ('201215121 ','2',85);
INSERT  INTO SC(Sno,Cno,Grade) VALUES ('201215121 ','3',88);
INSERT  INTO SC(Sno,Cno,Grade) VALUES ('201215122 ','2',90);
INSERT  INTO SC(Sno,Cno,Grade) VALUES ('201215122 ','3',80);

程序的制作我是用Visual Studio,使用的语言为C#
仅展示功能代码,整个项目点击最后链接下载
相同代码仅在第一次注释

登录界面:
数据库实验:学生管理系统 C# / VS_第2张图片

public partial class FormLogin : Form
    {
        public FormLogin()
        {
            InitializeComponent();
            //在Combobox中添加选项,也可在设计界面添加
            comboIdentity.Items.Add("管理员");
            comboIdentity.Items.Add("学生");
        }
        
        //static类型+函数用于实现窗体间传递学生账号
        static String name;
        public string Get()
        {
            return name;
        }
        //点击确认
        private void OK_Click(object sender, EventArgs e)
        {
        	//取出账号和密码
            string username = textBoxUserName.Text.Trim();  
            string password = EncryptWithMD5(textBoxPassWord.Text.Trim()); 
            name = username;
			//未正确填入信息提示
            if (comboIdentity.Text != "学生" && comboIdentity.Text != "管理员")
            {
                MessageBox.Show("请选择身份!", "Tips", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }
            if (username == "")
            {
                MessageBox.Show("账号不能为空", "Tips", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                textBoxUserName.Focus();
                return;
            }
            if (textBoxPassWord.Text.Trim() == "")
            {
                MessageBox.Show("密码不能为空!", "Tips", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                textBoxPassWord.Focus();
                return;
            }
            if (textBox1.Text != code)
            {
                MessageBox.Show("验证码错误", "Tips", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                textBox1.Focus();
                return;
            }
            
            //连接数据库并打开
            string myConnString = "Data Source=.;Initial Catalog=GIAO;Persist Security Info=True;User ID=sa;Password=";//填入自设密码
            SqlConnection sqlConnection = new SqlConnection(myConnString);  //实例化连接对象
            sqlConnection.Open();
            string sql = "select Name,password,userIdentity from ID where Name = '" + username + "' and password = '" + password + "' and userIdentity = '" + comboIdentity.Text + "'";                                            //编写SQL命令
            SqlCommand sqlCommand = new SqlCommand(sql, sqlConnection);
            
			//检验是否存在账户
            SqlDataReader sqlDataReader = sqlCommand.ExecuteReader();
            if (sqlDataReader.HasRows)
            {
                MessageBox.Show("登陆成功!", "notice", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);             //登录成功
                //打开对应窗体
                if (comboIdentity.Text == "管理员")
                {
                    Mean mean = new Mean();
                    mean.Show();
                    this.Hide();
                }
                if (comboIdentity.Text == "学生")
                {
                    userStudent student = new userStudent();
                    student.Show();
                    this.Hide();
                }
            }
            else
            {
            	//提示错误,关闭DataReader和数据库
                MessageBox.Show("账号或密码错误!", "notice", MessageBoxButtons.OK, MessageBoxIcon.Error);
                sqlDataReader.Close();
                sqlConnection.Close();
                return;
            }
            //正常关闭DataReader和数据库
            sqlDataReader.Close();
            sqlConnection.Close();
        }

		//点击取消,退出程序
        private void Cancel_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

		//密码使用MD5加密
        public static string EncryptWithMD5(string source)
        {
            byte[] sor = Encoding.UTF8.GetBytes(source);
            MD5 md5 = MD5.Create();
            byte[] result = md5.ComputeHash(sor);
            StringBuilder strbul = new StringBuilder(40);
            for (int i = 0; i < result.Length; i++)
            {
                strbul.Append(result[i].ToString("x2"));//加密结果"x2"结果为32位,"x3"结果为48位,"x4"结果为64位
            }
            return strbul.ToString();
        }

        public string code;
		
		//点击注册
        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Register register = new Register();
            register.ShowDialog();
        }

		//获得验证码
        private void FormLogin_Load(object sender, EventArgs e)
        {
            //随机实例化 
            Random ran = new Random();
            int number;
            char code1;
            //取五个数 
            for (int i = 0; i < 5; i++)
            {
                number = ran.Next();
                if (number % 2 == 0)
                    code1 = (char)('0' + (char)(number % 10));
                else
                    code1 = (char)('A' + (char)(number % 26)); //转化为字符 

                this.code += code1.ToString();
            }
            label6.Text = code;
        }

		//点击忘记密码
        private void forget_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Forget f = new Forget();
            f.Show();
        }
	}

注册:
数据库实验:学生管理系统 C# / VS_第3张图片

    public partial class Register : Form
    {
        public Register()
        {
            InitializeComponent();
            //密钥问题
            comboQuestion.Items.Add("喜欢的食物?");
            comboQuestion.Items.Add("喜欢的颜色?");
            comboQuestion.Items.Add("对你影响很大的人?");
            comboQuestion.Items.Add("班主任的名字?");
        }

        private void OK_Click(object sender, EventArgs e)
        {
            string username = textBoxUserName.Text.Trim();  //取出账号
            string password = textBoxPassWord.Text.Trim();  //取出密码
            string question = comboQuestion.Text.Trim();    //取出密钥问题
            string anwser = Answer.Text.Trim();  //取出密钥答案
            string identity = comboBox1.Text.Trim();  //取出身份信息

            //未正确输入提示
            if (username == "") 
            {
                MessageBox.Show("账号不能为空","Tips",MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                textBoxUserName.Focus(); 
                return;
            } 
            if (password == "") 
            { 
                MessageBox.Show("密码不能为空!", "Tips",MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                textBoxPassWord.Focus(); 
                return; 
            }

            //处理密码
            if (textBoxPassWord.Text.Trim() != "")
            {
                //使用regex(正则表达式)进行格式设置 至少有数字、大写字母、小写字母各一个。最少3个字符、最长20个字符。
                Regex regex = new Regex(@"(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).{3,20}");

                if (regex.IsMatch(textBoxPassWord.Text))//判断格式是否符合要求
                {
                    //MessageBox.Show("输入密码格式正确!");
                }
                else
                {
                    MessageBox.Show("至少有数字、大写字母、小写字母各一个。最少3个字符、最长20个字符!");
                    textBoxPassWord.Focus();
                    return;
                }
            }

            //未正确输入提示
            if (textBoxPassWord2.Text.Trim() == "")
            {
                MessageBox.Show("确认密码不能为空!", "Tips", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                textBoxPassWord2.Focus();
                return;
            }
            if (String.Compare(textBoxPassWord2.Text.Trim(), textBoxPassWord.Text.Trim()) !=0)
            {
                MessageBox.Show("密码和确认密码不一致!", "Tips", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (anwser == "" || question == "") 
            {
                MessageBox.Show("必须设定密钥!", "Tips", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                Answer.Focus();
                return;
            }
            if (identity == "")
            {
                MessageBox.Show("请选择身份!", "Tips", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }
            if (picturePath == "")
            {
                MessageBox.Show("请上传图片!", "Tips", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            try
            {
                //连接数据库,编写数据库语言
                string connString = "Data Source=.;Initial Catalog=GIAO;Persist Security Info=True;User ID=sa;Password=";
                SqlConnection connection = new SqlConnection(connString);//创建connection对象
                string sql = "insert into ID (Name,password ,Answer,Birthday , userIdentity , userPhoto,Question ) " +
                                                        "values (@name, @password,@answer,@birthday,@useridentity,@userphoto,@question)";
                SqlCommand command = new SqlCommand(sql, connection);
                SqlParameter sqlParameter = new SqlParameter("@name", textBoxUserName.Text);
                command.Parameters.Add(sqlParameter);
                sqlParameter = new SqlParameter("@password", EncryptWithMD5(textBoxPassWord.Text));
                command.Parameters.Add(sqlParameter);
                sqlParameter = new SqlParameter("@answer", Answer.Text);
                command.Parameters.Add(sqlParameter);
                sqlParameter = new SqlParameter("@birthday", dateTimePicker1.Value);
                command.Parameters.Add(sqlParameter);
                sqlParameter = new SqlParameter("@useridentity", comboBox1.Text);
                command.Parameters.Add(sqlParameter);
                sqlParameter = new SqlParameter("@userphoto", SqlDbType.VarBinary, mybyte.Length, ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Current, mybyte);
                command.Parameters.Add(sqlParameter);
                sqlParameter = new SqlParameter("@question", comboQuestion.Text);
                command.Parameters.Add(sqlParameter);

                //打开数据库连接
                connection.Open();

                //检测账号是否合格
                if (identity == "学生")
                {
                    String id = "select * from Student where Sno ='" + username + "'";
                    SqlCommand comm = new SqlCommand(id, connection);
                    SqlDataReader m = comm.ExecuteReader();
                    if (!m.HasRows)  
                    {
                        MessageBox.Show("不存在该学生账号!", "Tips", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        m.Close();
                        return;
                    }
                    m.Close();
                    String select_by_id = "select * from ID where Name ='" + username + "'";
                    SqlCommand com = new SqlCommand(select_by_id, connection);
                    SqlDataReader w = com.ExecuteReader();
                    if (w.HasRows)
                    {
                        MessageBox.Show("该学生账号已注册!", "Tips", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        w.Close();
                        return;
                    }
                    w.Close();
                }
                if (identity == "管理员")
                {
                    String select_by_id = "select * from ID where Name ='" + username + "'";
                    SqlCommand comm = new SqlCommand(select_by_id, connection);
                    SqlDataReader m = comm.ExecuteReader();
                    if (m.HasRows)
                    {
                        MessageBox.Show("账号重复!", "Tips", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        m.Close();
                        return;
                    }
                    m.Close();
                }
                command.ExecuteNonQuery();
                connection.Close();
                MessageBox.Show("注册成功!", "Tips", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }
            this.Close();
        }

        public static string EncryptWithMD5(string source)
        {
            byte[] sor = Encoding.UTF8.GetBytes(source);
            MD5 md5 = MD5.Create();
            byte[] result = md5.ComputeHash(sor);
            StringBuilder strbul = new StringBuilder(40);
            for (int i = 0; i < result.Length; i++)
            {
                strbul.Append(result[i].ToString("x2"));//加密结果"x2"结果为32位,"x3"结果为48位,"x4"结果为64位
            }
            return strbul.ToString();
        }

        private void Cancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        //选择图片
        public Byte[] mybyte = new byte[0];
        string picturePath="";
        private void button3_Click(object sender, EventArgs e)
        {
            //打开浏览图片对话框
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.ShowDialog();
            picturePath = openFileDialog.FileName;//获取图片路径
                                                         //文件的名称,每次必须更换图片的名称,这里很为不便
                                                         //创建FileStream对象
            if(picturePath=="")
            {
                return;
            }
            FileStream fs = new FileStream(picturePath, FileMode.Open, FileAccess.Read);
            //声明Byte数组
            mybyte = new byte[fs.Length];
            //读取数据
            fs.Read(mybyte, 0, mybyte.Length);
            pictureBox1.Image = Image.FromStream(fs);
            fs.Close();
        }
    }

修改密码:
数据库实验:学生管理系统 C# / VS_第4张图片

public partial class Forget : Form
    {
        //连接数据库
        SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=GIAO;User ID=sa;Password=");

        public Forget()
        {
            InitializeComponent();
        }

        //检查账号并获取密钥问题
        private void button3_Click(object sender, EventArgs e)
        {
            if (textBoxUserName.Text == "")
            {
                MessageBox.Show("账号不能为空", "Tips", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                textBoxUserName.Focus();
                return;
            }
            con.Open();
            
            String id = "select * from ID where Name ='" + textBoxUserName.Text + "'";
            SqlCommand comm = new SqlCommand(id, con);
            SqlDataReader m = comm.ExecuteReader();
            if (!m.HasRows)
            {
                MessageBox.Show("不存在该账号!", "Tips", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                m.Close();
                con.Close();
                return;
            }
            m.Close();
            SqlDataAdapter sda = new SqlDataAdapter(id, con);
            DataTable dt = new DataTable();
            sda.Fill(dt);
            label1.Text = dt.Rows[0][6].ToString();
            con.Close();
        }

        
        private void button1_Click(object sender, EventArgs e)
        {
            //检验账号、密码,部分代码同之前窗口
            if (textBoxUserName.Text == "")
            {
                MessageBox.Show("账号不能为空", "Tips", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                textBoxUserName.Focus();
                return;
            }
            if (Answer.Text == "")
            {
                MessageBox.Show("请输入密钥答案", "Tips", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                Answer.Focus();
                return;
            }
            con.Open();
            String id = "select * from ID where Name ='" + textBoxUserName.Text + "'";
            SqlCommand comm = new SqlCommand(id, con);
            SqlDataReader m = comm.ExecuteReader();
            if (!m.HasRows)
            {
                MessageBox.Show("不存在该学生账号!", "Tips", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                m.Close();
                con.Close();
                return;
            }
            m.Close();
            SqlDataAdapter sda = new SqlDataAdapter(id, con);
            DataTable dt = new DataTable();
            sda.Fill(dt);
            String s = dt.Rows[0][2].ToString();
            if (String.Compare(Answer.Text.Trim(), s.Trim()) != 0)
            {
                MessageBox.Show("答案错误!", "Tips", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                m.Close();
                con.Close();
                return;
            }
            if (textBoxPassWord.Text == "")
            {
                MessageBox.Show("新密码不能为空!", "Tips", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                textBoxPassWord.Focus();
                con.Close();
                return;
            }
            if (textBoxPassWord.Text.Trim() != "")
            {
                //使用regex(正则表达式)进行格式设置 至少有数字、大写字母、小写字母各一个。最少3个字符、最长20个字符。
                Regex regex = new Regex(@"(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).{3,20}");

                if (regex.IsMatch(textBoxPassWord.Text))//判断格式是否符合要求
                {
                    //MessageBox.Show("输入密码格式正确!");
                }
                else
                {
                    MessageBox.Show("至少有数字、大写字母、小写字母各一个。最少3个字符、最长20个字符!");
                    textBoxPassWord.Focus();
                    con.Close();
                    return;
                }
            }
            if (textBoxPassWord2.Text.Trim() == "")
            {
                MessageBox.Show("确认密码不能为空!", "Tips", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                textBoxPassWord2.Focus();
                con.Close();
                return;
            }
            if (String.Compare(textBoxPassWord2.Text.Trim(), textBoxPassWord.Text.Trim()) != 0)
            {
                MessageBox.Show("密码和确认密码不一致!", "Tips", MessageBoxButtons.OK, MessageBoxIcon.Error);
                textBoxPassWord2.Focus();
                con.Close();
                return;
            }
            string insertStr = "UPDATE ID SET password = '" + EncryptWithMD5(textBoxPassWord.Text) + "' WHERE Name = '" + textBoxUserName.Text.Trim() + "'";
            SqlCommand cmd = new SqlCommand(insertStr, con);
            cmd.ExecuteNonQuery();
            MessageBox.Show("密码修改成功!", "Tips", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
            con.Close();
            this.Close();
        }

        public static string EncryptWithMD5(string source)
        {
            byte[] sor = Encoding.UTF8.GetBytes(source);
            MD5 md5 = MD5.Create();
            byte[] result = md5.ComputeHash(sor);
            StringBuilder strbul = new StringBuilder(40);
            for (int i = 0; i < result.Length; i++)
            {
                strbul.Append(result[i].ToString("x2"));//加密结果"x2"结果为32位,"x3"结果为48位,"x4"结果为64位
            }
            return strbul.ToString();
        }

        //退出
        private void CLOSE_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }

管理员界面:
数据库实验:学生管理系统 C# / VS_第5张图片

public partial class Mean : Form
    {
        String SqlString;
        SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=GIAO;User ID=sa;Password=");
        
        public Mean()
        {
            InitializeComponent();
            //combobox列表显示数据库中的表
            try
            {
                con.Open();
            }
            catch
            {
                MessageBox.Show("连接失败!", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            //声明一个SQLcommand对象
            SqlCommand sqlcmd = new SqlCommand("SELECT Name FROM SysObjects Where XType='U' ORDER BY Name", con);
            //用DataAdapter声明一个对象
            SqlDataAdapter sda = new SqlDataAdapter();
            //执行查询语句
            sda.SelectCommand = sqlcmd;
            //创建一个数据集对象
            DataSet ds = new DataSet();
            //调用DataAdapter对象的Fill()方法来填充数据集
            sda.Fill(ds, "Name");
            //选定combobox显示的成员及将Name这一列显示在combobox中
            comboDataTable.DisplayMember = "Name";
            //绑定combobox的数据集
            comboDataTable.DataSource = ds.Tables["Name"];
        }
        
        private void OK_Click(object sender, EventArgs e)
        {
            //显示选择的表
            SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=GIAO;User ID=sa;Password=1234");
            SqlString = "select * from " + this.comboDataTable.Text;
            //加载数据并显示
            try
            {
                //查询条件和SqlConnection连接
                SqlCommand cmd = new SqlCommand(SqlString, con); 
                //数据适配器
                SqlDataAdapter sda = new SqlDataAdapter();
                sda.SelectCommand = cmd;
                //DataTable存储数据
                DataTable dt = new DataTable();
                sda.Fill(dt);
                dataGridView1.DataSource = dt;
            }
            catch
            { 
            
            } 
            finally
            {
                con.Close(); 
            }
        }

        private void close_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }
        //跳转修改窗口
        private void button1_Click(object sender, EventArgs e)
        {
            if(String.Compare(this.comboDataTable.Text,"Student")==0)
            {
                Student s = new Student();
                s.Show();
                this.Hide();
            }
            else if (String.Compare(this.comboDataTable.Text, "ID") == 0)
            {
                MessageBox.Show("无权修改此表!", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            else if (String.Compare(this.comboDataTable.Text, "SC") == 0)
            {
                SC s = new SC();
                s.Show();
                this.Hide();
            }
            else if (String.Compare(this.comboDataTable.Text, "Course") == 0)
            {
                Course s = new Course();
                s.Show();
                this.Hide();
            }
        }

        //返回登录界面
        private void button5_Click(object sender, EventArgs e)
        {
            this.Close();
            FormLogin f = new FormLogin();
            f.Show();
        }
    }

对三张表的增删改查处理方式相同,以Student表为例
数据库实验:学生管理系统 C# / VS_第6张图片

public partial class Student : Form
    {
        public Student()
        {
            InitializeComponent();
        }
        //返回上一界面
        private void close_Click(object sender, EventArgs e)
        {
            Mean s = new Mean();
            s.Show();
            this.Hide();
        }
        //连接数据库
        SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=GIAO;User ID=sa;Password=");
        
        //增加
        private void insert_Click(object sender, EventArgs e)
        {
            //取出信息
            String StuID = textBox1.Text.Trim();
            String StuName = textBox2.Text.Trim();
            String StuSex = textBox3.Text.Trim();
            String StuAge = textBox4.Text.Trim();
            String StuSdept = textBox5.Text.Trim();
            try
            {
                //打开数据库,编辑SQL语言并执行
                con.Open();
                string insertStr = "INSERT INTO  Student (Sno,Sname,Ssex,Sage,Sdept)" +
                                   "VALUES ('" + StuID + "','" + StuName + "','" + StuSex + "','" + StuAge + "'," + StuSdept + ")";
                SqlCommand cmd = new SqlCommand(insertStr, con);
                cmd.ExecuteNonQuery();
            }
            catch
            {
                MessageBox.Show("输入数据违反要求!","ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                con.Close();
            }
            //刷新dataDridView中展示的表
            this.studentTableAdapter.Fill(this.gIAODataSet.Student);
        }

        private void Student_Load(object sender, EventArgs e)
        {
            // TODO: 这行代码将数据加载到表“gIAODataSet.Student”中。您可以根据需要移动或删除它。
            this.studentTableAdapter.Fill(this.gIAODataSet.Student);
            //toolTip插件实现鼠标停留按钮显示对应文字
            toolTip1.SetToolTip(delete, "请在表中选中整行,点击删除");
            toolTip1.SetToolTip(insert, "请在上方输入信息,点击添加");
            toolTip1.SetToolTip(update, "请在上方输入学生学号,选择性修改剩余信息,点击修改");
            toolTip1.SetToolTip(select, "请在上方输入一项或多项信息,点击查询");
            toolTip1.SetToolTip(button1, "显示完整表");
        }

        //删除
        private void delete_Click(object sender, EventArgs e)
        {
            DialogResult dr = MessageBox.Show("确认删除?", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation);
            if(dr==DialogResult.OK)
            {
                try
                {
                    con.Open();
                    string select_id = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();//选择的当前行第一列的值,也就是ID
                    string delete_by_id = "delete from Student where Sno=" + select_id;//sql删除语句
                    SqlCommand cmd = new SqlCommand(delete_by_id, con);
                    cmd.ExecuteNonQuery();
                }
                catch
                {
                    MessageBox.Show("请正确选择行!", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                finally
                {
                    con.Close();
                }
                this.studentTableAdapter.Fill(this.gIAODataSet.Student);
            }
        }

        //修改
        private void update_Click(object sender, EventArgs e)
        {
            String StuID = textBox1.Text.Trim();
            String StuName = textBox2.Text.Trim();
            String StuSex = textBox3.Text.Trim();
            String StuAge = textBox4.Text.Trim();
            String StuSdept = textBox5.Text.Trim();
            SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=GIAO;User ID=sa;Password=");
            try
            {
                con.Open();
                if (StuID == "")
                {
                    MessageBox.Show("学号不能为空!", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                if (StuName != "")
                {
                    string insertStr = "UPDATE Student SET Sname = '" + StuName + "' WHERE Sno = '" + StuID + "'";
                    SqlCommand cmd = new SqlCommand(insertStr, con);
                    cmd.ExecuteNonQuery();
                }
                if (StuSex != "")
                {
                    string insertStr = "UPDATE Student SET Ssex = '" + StuSex + "' WHERE Sno = '" + StuID + "'";
                    SqlCommand cmd = new SqlCommand(insertStr, con);
                    cmd.ExecuteNonQuery();
                }
                if (StuAge != "")
                {
                    string insertStr = "UPDATE Student SET Sage = '" + StuAge + "' WHERE Sno = '" + StuID + "'";
                    SqlCommand cmd = new SqlCommand(insertStr, con);
                    cmd.ExecuteNonQuery();
                }
                if (StuSdept != "")
                {
                    string insertStr = "UPDATE Student SET Sdept = '" + StuSdept + "' WHERE Sno = '" + StuID + "'";
                    SqlCommand cmd = new SqlCommand(insertStr, con);
                    cmd.ExecuteNonQuery();
                }
            }
            catch
            {
                MessageBox.Show("输入数据违反要求!", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                con.Close();
            }
            MessageBox.Show("修改成功!", "Tips", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
            this.studentTableAdapter.Fill(this.gIAODataSet.Student);
        }

        //清空输入
        private void clear_Click(object sender, EventArgs e)
        {
            textBox1.Text = "";
            textBox2.Text = "";
            textBox3.Text = "";
            textBox4.Text = "";
            textBox5.Text = "";
        }

        //查询
        private void select_Click(object sender, EventArgs e)
        {
            String StuID = textBox1.Text.Trim();
            String StuName = textBox2.Text.Trim();
            String StuSex = textBox3.Text.Trim();
            String StuAge = textBox4.Text.Trim();
            String StuSdept = textBox5.Text.Trim();
            try
            {
                con.Open();
                String select_by_id = "select * from Student where ";
                int flag = 0;     
                if (StuID != "")
                {
                    if (flag == 0)
                    {
                        select_by_id += "Sno='" + StuID + "'";
                        flag = 1;
                    }
                    else
                    {
                        select_by_id += "AND Sno='" + StuID + "'";
                    }
                }
                if (StuName != "")
                {
                    if (flag == 0)
                    {
                        select_by_id += "Sname='" + StuName + "'";
                        flag = 1;
                    }
                    else
                    {
                        select_by_id += "AND Sname='" + StuName + "'";
                    }
                }
                if (StuSex != "")
                {
                    if (flag == 0)
                    {
                        select_by_id += "Ssex='" + StuSex + "'";
                        flag = 1;
                    }
                    else
                    {
                        select_by_id += "AND Ssex='" + StuSex + "'";
                    }
                }
                if (StuAge != "")
                {
                    if (flag == 0)
                    {
                        select_by_id += "Sage='" + StuAge + "'";
                        flag = 1;
                    }
                    else
                    {
                        select_by_id += "AND Sage='" + StuAge + "'";
                    }
                }
                if (StuSdept != "")
                {
                    if (flag == 0)
                    {
                        select_by_id += "Sdept='" + StuSdept + "'";
                        flag = 1;
                    }
                    else
                    {
                        select_by_id += "AND Sdept='" + StuSdept + "'";
                    }
                }
                if(select_by_id == "select * from Student where ")
                {
                    MessageBox.Show("输入为空");
                    return;
                }
                SqlCommand sqlCommand = new SqlCommand(select_by_id, con);
                SqlDataReader sqlDataReader = sqlCommand.ExecuteReader();
                BindingSource bindingSource = new BindingSource();
                bindingSource.DataSource = sqlDataReader;
                dataGridView1.DataSource = bindingSource;
            }
            catch
            {
                MessageBox.Show("查询语句有误,请认真检查SQL语句!", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                con.Close();
            }
        }

        //刷新表,显示完整表
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                con.Open();
                String select_by_id = "select * from Student";
                SqlCommand sqlCommand = new SqlCommand(select_by_id, con);
                SqlDataReader sqlDataReader = sqlCommand.ExecuteReader();
                BindingSource bindingSource = new BindingSource();
                bindingSource.DataSource = sqlDataReader;
                dataGridView1.DataSource = bindingSource;
            }
            catch
            {
                MessageBox.Show("失败!", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                con.Close();
            }
        }
    }

学生基本信息界面、选课界面、查分界面为选项卡,仅对个人相关信心读写:
数据库实验:学生管理系统 C# / VS_第7张图片

public partial class userStudent : Form
    {
        SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=GIAO;User ID=sa;Password=");
        
        public userStudent()
        {
            InitializeComponent();
            //实现基本信息的显示
            FormLogin m = new FormLogin();
            labelName.Text = m.Get();
            String select_by_id = "select * from ID where Name='" + labelName.Text + "'";
            SqlDataAdapter sda = new SqlDataAdapter(select_by_id, con);
            DataTable dt = new DataTable();
            sda.Fill(dt);
            datatime.Text = dt.Rows[0][3].ToString();
            Byte[] picture =new Byte[0];
            picture = (Byte[])(dt.Rows[0][5]);
            MemoryStream stream = new MemoryStream(picture);
            pictureBox1.Image = Image.FromStream(stream);
            
        }
        
        private void userStudent_Load(object sender, EventArgs e)
        {
            this.courseTableAdapter.Fill(this.gIAODataSet.Course);
        }

        //添加课程,思路同管理员添加
        private void buttonAdd_Click(object sender, EventArgs e)
        {
            if (textBox1.Text == "")
            {
                MessageBox.Show("请输入课程号!", "Tips", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }
            try
            {
                con.Open();
                String s;
                String select_by_id = "select * from SC where Sno='" + labelName.Text + "' and Cno='" + textBox1.Text + "'";
                String select = "select * from Course where Cno='"+ textBox1.Text + "'";
                SqlCommand comm = new SqlCommand(select, con);
                SqlDataReader m = comm.ExecuteReader();
                if (!m.HasRows)
                {
                    MessageBox.Show("不存在该课程!", "Tips", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    m.Close();
                    con.Close();
                    return;
                }
                m.Close();
                SqlCommand co = new SqlCommand(select_by_id, con);
                SqlDataReader w = co.ExecuteReader();
                if (w.HasRows) 
                {
                    MessageBox.Show("已选修该课程!", "Tips", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    w.Close();
                    con.Close();
                    return;
                }
                w.Close();
                string insertStr = "INSERT INTO  SC (Sno,Cno,Grade)" +
                                   "VALUES ('" + labelName.Text + "','" + textBox1.Text + "',NULL)";
                SqlCommand cmd = new SqlCommand(insertStr, con);
                cmd.ExecuteNonQuery();
                MessageBox.Show("选课成功!");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                con.Close();
            }
        }

        //删除课程,思路同管理员添加
        private void buttonDelete_Click(object sender, EventArgs e)
        {
            if (textBox1.Text == "")
            {
                MessageBox.Show("请输入课程号!", "Tips", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }
            try
            {
                con.Open();

                String select_by_id = "select * from SC where Sno='" + labelName.Text + "' and Cno='" + textBox1.Text + "'";
                SqlCommand com = new SqlCommand(select_by_id, con);
                SqlDataReader w = com.ExecuteReader();
                if (!w.HasRows)
                {
                    MessageBox.Show("未选修该课程!", "Tips", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    w.Close();
                    return;
                }
                w.Close();
                string deleteStr = "delete from SC where Sno='" + labelName.Text + "' and Cno='" + textBox1.Text + "'";
                SqlCommand cmd = new SqlCommand(deleteStr, con);
                cmd.ExecuteNonQuery();
                MessageBox.Show("退课成功!");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                con.Close();
            }
        }

        //显示已选课程,思路同管理员查询
        private void button1_Click(object sender, EventArgs e)
        {
            String SqlString = "select SC.Sno,SC.Cno,Course.Cname from SC,Course where SC.Sno='" + labelName.Text + "' and SC.Cno=Course.Cno";
            //加载数据并显示
            try
            {
                //查询条件和SqlConnection连接
                SqlCommand cmd = new SqlCommand(SqlString, con);
                //数据适配器
                SqlDataAdapter sda = new SqlDataAdapter();
                sda.SelectCommand = cmd;
                //DataTable存储数据
                DataTable dt = new DataTable();
                sda.Fill(dt);
                dataGridView3.DataSource = dt;
            }
            catch
            {

            }
            finally
            {
                con.Close();
            }
        }

        //显示已选课程成绩,思路同管理员查询
        private void button2_Click(object sender, EventArgs e)
        {
            String SqlString = "select SC.Sno,SC.Cno,Course.Cname,SC.Grade from SC,Course where SC.Sno='" + labelName.Text + "' and SC.Cno=Course.Cno";
            //加载数据并显示
            try
            {
                //查询条件和SqlConnection连接
                SqlCommand cmd = new SqlCommand(SqlString, con);
                //数据适配器
                SqlDataAdapter sda = new SqlDataAdapter();
                sda.SelectCommand = cmd;
                //DataTable存储数据
                DataTable dt = new DataTable();
                sda.Fill(dt);
                dataGridView2.DataSource = dt;
            }
            catch
            {

            }
            finally
            {
                con.Close();
            }
        }

        //按课程号查询分数,思路同管理员查询
        private void select_Click(object sender, EventArgs e)
        {
            try
            {
                con.Open();
                if (textBox2.Text == "")
                {
                    MessageBox.Show("请输入课程号!", "Tips", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }
                String select_by_id = "select SC.Sno,SC.Cno,Course.Cname,SC.Grade from SC,Course where SC.Cno='" + textBox2.Text + "'and SC.Sno='" + labelName.Text + "' and SC.Cno = Course.Cno";
                SqlCommand com = new SqlCommand(select_by_id, con);
                SqlDataReader w = com.ExecuteReader();
                if (!w.HasRows)
                {
                    MessageBox.Show("未选修该课程!", "Tips", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    w.Close();
                    return;
                }
                w.Close();
                //查询条件和SqlConnection连接
                SqlCommand cmd = new SqlCommand(select_by_id, con);
                //数据适配器
                SqlDataAdapter sda = new SqlDataAdapter();
                sda.SelectCommand = cmd;
                //DataTable存储数据
                DataTable dt = new DataTable();
                sda.Fill(dt);
                dataGridView2.DataSource = dt;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                con.Close();
            }
        }

        //删除个人账号并返回登录界面
        private void button3_Click(object sender, EventArgs e)
        {
            DialogResult dr = MessageBox.Show("确认删除?", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation);
            if (dr == DialogResult.OK)
            {
                try
                {
                    con.Open();
                    string delete_by_id = "delete from ID where Name='" + labelName.Text + "'";//sql删除语句
                    SqlCommand cmd = new SqlCommand(delete_by_id, con);
                    cmd.ExecuteNonQuery();
                }
                catch
                {
                    MessageBox.Show("删除失败!", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    con.Close();
                    return;
                }
                finally
                {
                    con.Close();
                }
            }
            MessageBox.Show("删除成功!");
            this.Close();
            FormLogin f = new FormLogin();
            f.Show();
        }

        //更改照片
        public Byte[] mybyte = new byte[0];
        string picturePath = "";
        private void button4_Click(object sender, EventArgs e)
        {
            //打开浏览图片对话框
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.ShowDialog();
            picturePath = openFileDialog.FileName;//获取图片路径
                                                  //文件的名称,每次必须更换图片的名称,这里很为不便
                                                  //创建FileStream对象
            if (picturePath == "")
            {
                return;
            }
            FileStream fs = new FileStream(picturePath, FileMode.Open, FileAccess.Read);
            //声明Byte数组
            mybyte = new byte[fs.Length];
            //读取数据
            fs.Read(mybyte, 0, mybyte.Length);
            pictureBox1.Image = Image.FromStream(fs);
            fs.Close();

            string sql = "UPDATE ID SET userPhoto = @userphoto WHERE Name = '" + labelName.Text + "'";
            SqlCommand command = new SqlCommand(sql, con);
            SqlParameter sqlParameter = new SqlParameter("@userphoto", SqlDbType.VarBinary, mybyte.Length, ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Current, mybyte);
            command.Parameters.Add(sqlParameter);
            con.Open();

            command.ExecuteNonQuery();
            con.Close();
            MessageBox.Show("上传成功!", "Tips", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
            
        }

        private void button5_Click(object sender, EventArgs e)
        {
            this.Close();
            FormLogin f = new FormLogin();
            f.Show();
        }

        private void button6_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }

项目代码:https://download.csdn.net/download/MooM_X/12466765

视频讲解:https://www.bilibili.com/video/BV1NT4y1g7Jr?from=search&seid=2757448567491311244

注:背景是我根据我窗口的大小在网上下载资源创作的图片,已打包。请记得修改数据库连接语句,避免项目运行时出错!

你可能感兴趣的:(数据库实验:学生管理系统 C# / VS)