C#连接SQL Server数据库实现简易的学生成绩管理系统

今天做了一个学生成绩管理系统,包括了成绩输入成绩输出、成绩查询、修改成绩、删除成绩信息等功能。对于有一定基础知识的同学来说,也很容易理解。

一、配置SQL数据库连接信息

1、由于这个程序连接了SQL Server数据库,所以需要配置一下相关数据,创建一个“账号登录”数据库,新建一个“登录注册表”和“学生成绩表”,并记住这个服务器名称,等下会用到,如下图所示。

C#连接SQL Server数据库实现简易的学生成绩管理系统_第1张图片

登录注册表设置两个列名:username(账号)和password(密码)以及对应的数据类型(可自定义)。

C#连接SQL Server数据库实现简易的学生成绩管理系统_第2张图片

学生成绩表设置5个列名:Name(学生成绩)、Number(学生学号)、Chinese(语文成绩)、Math(数学成绩)、English(英语成绩)和相应的数据类型。

C#连接SQL Server数据库实现简易的学生成绩管理系统_第3张图片


C#连接SQL Server数据库实现简易的学生成绩管理系统_第4张图片
2、然后打开VS2019,新建一个控制台程序,在里面设置一下App.config的SQL数据库连接信息,如下图所示。

C#连接SQL Server数据库实现简易的学生成绩管理系统_第5张图片

App.config里面的代码格式:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>

    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8" />
	</startup>
	
	<connectionStrings>
		<add name="sqlserver" connectionString="server=SQLEXPRESS;database=账号登录;integrated security = true;"/>
		//这是以windows身份验证登录连接,无需用户名和密码,SQLEXPRESS是服务器名称,“账号登录”是新建的数据库名称.
	</connectionStrings>
	
</configuration>

二、相关的源代码

以下为该程序的全部源代码,创建了两个类,分别包括了账号登录程序和学生成绩管理系统两大功能。

全部源代码


using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Security.Cryptography;
using System.Text;

namespace CT123
{
    class Account	//账号登录
    {
        private string MD5Encrypt(string rawPass, string salt)   //MD5加盐加密操作
        {
            MD5 md5 = MD5.Create();
            byte[] bs = Encoding.UTF8.GetBytes(rawPass + salt);
            byte[] hs = md5.ComputeHash(bs);
            StringBuilder stb = new StringBuilder();
            foreach (byte b in hs)
            {
                stb.Append(b.ToString("x2"));
            }
            return stb.ToString();
        }

        //#############################################################################################
        private readonly string Stu = ConfigurationManager.ConnectionStrings["sqlserver"].ConnectionString;     //设置数据库连接对象

        private void Login()     //登录功能
        {
            Console.WriteLine("\n--------- 1.账号登录 ---------");
            SqlConnection conn = new SqlConnection(Stu);
            Console.Write("请输入账号:");
            string username = Console.ReadLine().Trim().Trim();
            Console.Write("请输入密码:");
            string password = Console.ReadLine().Trim().Trim();
            while (true)
            {
                conn.Open();
                SqlCommand cmd = conn.CreateCommand();
                cmd.CommandText = "select * from 登录注册表 where username='" + username + "'";
                SqlDataReader sdt = cmd.ExecuteReader();
                if (Equals(username, ""))
                {
                    Console.Write("账号不得为空!\n请输入账号:");
                    username = Console.ReadLine().Trim().Trim();
                }
                else if (Equals(password, ""))
                {
                    Console.Write("密码不得为空!\n请输入密码");
                    password = Console.ReadLine().Trim();
                }
                else if (sdt.Read())    //读取到记录
                {
                    string result = sdt.GetString(sdt.GetOrdinal("password"));
                    if (MD5Encrypt(password, username).Equals(result))
                    {
                        Console.WriteLine("登录成功!");
                        conn.Close();         //关闭数据库连接
                        Grade st = new Grade();
                        st.GradeTable();
                    }
                    else
                    {
                        Console.WriteLine("账号密码错误!");
                        conn.Close();
                        Login();
                    }
                }
                else
                {
                    YesOrNo();
                }
                conn.Close();
            }
        }

        private void YesOrNo()
        {
            Console.WriteLine("\n账号不存在,是否选择注册一个新账号?\n1、是;2、否");
            string num = Console.ReadLine().Trim();
            switch (num)
            {
                case "1": Register(); break;
                case "2": Main2(); break;
                default:
                    {
                        Console.WriteLine("请重新选择!");
                        YesOrNo();
                    }; break;
            }
        }

        //#############################################################################################

        private void Register()  //账号注册功能
        {
            Console.WriteLine("\n--------- 2.账号注册 ---------");
            SqlConnection conn = new SqlConnection(Stu);
            Console.Write("请输入注册账号:");
            string newusername = Console.ReadLine().Trim();
            Console.Write("请输入账号密码:");
            string password = Console.ReadLine().Trim();
            Console.Write("请确认账号密码:");
            string repassword = Console.ReadLine().Trim();
            while (true)
            {
                conn.Open();
                string sql = "Select username from 登录注册表 where username='" + newusername + "'";
                SqlCommand cmd = new SqlCommand(sql, conn);      //判断账号是否已存在
                cmd.CommandType = CommandType.Text;
                SqlDataReader sdt = cmd.ExecuteReader();
                if (Equals(newusername, ""))
                {
                    Console.Write("注册账号不得为空!\n请输入注册账号:");
                    newusername = Console.ReadLine().Trim();
                }
                else if (Equals(password, ""))
                {
                    Console.Write("账号密码不得为空!\n请输入账号密码:");
                    password = Console.ReadLine().Trim();
                }
                else if (repassword.Equals("") || !password.Equals(repassword))
                {
                    Console.Write("请重新确认密码:");
                    repassword = Console.ReadLine().Trim();
                }
                /*  else if (newusername.Length < 8)
                  {
                      Console.WriteLine("请输入8位以上的新用户名!");
                      newusername =Console.ReadLine().Trim();
                  }
                  else if (Regex.IsMatch(password.ToString(), @"^\w+_$") == false)
                  {
                      Console.Write("请输入8~16位由字母、数字和下划线组成的密码:");
                      password =Console.ReadLine().Trim();
                  }
                  else if (password.Length < 8 || password.Length > 16)
                  {
                      Console.WriteLine("请输入8~16位由字母、数字和下划线组成的密码!");
                      password =Console.ReadLine().Trim();
                  }*/

                else
                {
                    if (sdt.Read())
                    {
                        Console.WriteLine("该账号已注册,请重新注册账号!");
                        Register();
                    }
                    else
                    {
                        //插入的信息分别为账号,密文
                        Insert(newusername, MD5Encrypt(password, newusername));
                        //调用函数Insert()保存注册信息到数据库
                        conn.Close();
                    }
                }
                conn.Close();
            }
        }

        private void Insert(string txt1, string txt2)   //数据库插入注册成功后的账号信息
        {
            SqlConnection conn = new SqlConnection(Stu);
            conn.Open();
            try
            {
                string InsertStr = string.Format("insert into 登录注册表 values('{0}','{1}')", txt1, txt2);
                SqlCommand comm = conn.CreateCommand();
                comm.CommandText = InsertStr;
                SqlCommand mycom = new SqlCommand(InsertStr, conn);
                mycom.ExecuteNonQuery();
                Console.WriteLine("账号注册成功!");
                conn.Close();
                Main2();
            }
            catch (Exception ex)
            {
                Console.WriteLine("账号注册失败!");
                Console.WriteLine(ex.Message);
                conn.Close();
                Main2();
            }
            conn.Close();
        }


        //##############################################################################################

        private void Change()    //修改密码
        {
            Console.WriteLine("\n--------- 3.修改密码 ---------");
            SqlConnection conn = new SqlConnection(Stu);
            Console.Write("请输入账号:");
            string username = Console.ReadLine().Trim();
            Console.Write("请输入旧密码:");
            string oldpassword = Console.ReadLine().Trim();
            Console.Write("请输入新密码:");
            string newpassword = Console.ReadLine().Trim();
            while (true)
            {
                conn.Open();
                string sql = "Select password from 登录注册表 where username='" + username + "'";
                SqlCommand cmd = new SqlCommand(sql, conn);     //调用登录窗体Form1参数username,判断当前账号密码是否正确
                SqlDataReader reader = cmd.ExecuteReader();
                if (Equals(username, ""))
                {
                    Console.Write("账号不得为空!\n请输入账号:");
                    username = Console.ReadLine().Trim();
                }
                else if (Equals(oldpassword, ""))
                {
                    Console.Write("密码不得为空!\n请输入旧密码:");
                    oldpassword = Console.ReadLine().Trim();
                }
                else if (Equals(newpassword, ""))
                {
                    Console.Write("密码不得为空!\n请输入新密码:");
                    newpassword = Console.ReadLine().Trim();
                }
                else if (oldpassword.Equals(newpassword))
                {
                    Console.Write("新旧密码相同,请重新输入密码:");
                    oldpassword = Console.ReadLine().Trim();
                }
                else if (reader.Read())
                {
                    string result = reader["password"].ToString();  //读取到的密码
                    if (MD5Encrypt(oldpassword, username).Equals(result))
                    {
                        ChangeSave(username, MD5Encrypt(newpassword, username));
                        //调用Change()函数方法保存修改后的账号信息到数据库
                        conn.Close();
                    }
                    else
                    {
                        Console.WriteLine("账号密码错误!");
                        Change();
                    }
                }
                else
                {
                    YesOrNo();
                }
                conn.Close();
            }
        }

        private void ChangeSave(string txt1, string txt2)     //数据库保存修改后的账号信息
        {
            SqlConnection conn = new SqlConnection(Stu);
            conn.Open();
            try
            {
                string InsertStr = string.Format("update 登录注册表 set password='{0}' WHERE username='{1}';", txt2.ToString(), txt1.ToString());
                SqlCommand comm = conn.CreateCommand();
                SqlCommand mycom = new SqlCommand(InsertStr, conn);
                mycom.ExecuteNonQuery();
                Console.WriteLine("账号密码修改成功!");
                conn.Close();
                Main2();
            }
            catch (Exception ex)
            {
                Console.WriteLine("账号密码修改失败!");
                Console.WriteLine(ex.Message);
                conn.Close();
                Main2();
            }
        }

        //###################################################################################

        private void Delete()    //账号注销
        {
            Console.WriteLine("\n--------- 4.账号注销 ---------");
            SqlConnection conn = new SqlConnection(Stu);
            Console.Write("请输入账号:");
            string username = Console.ReadLine().Trim();
            Console.Write("请输入密码:");
            string password = Console.ReadLine().Trim();
            while (true)
            {
                conn.Open();
                string sql = "Select password from 登录注册表 where username='" + username + "'";
                SqlCommand cmd = new SqlCommand(sql, conn);     //判断当前账号密码是否正确
                cmd.CommandType = CommandType.Text;
                SqlDataReader reader = cmd.ExecuteReader();
                if (Equals(username, ""))
                {
                    Console.Write("账号不得为空!\n请输入账号:");
                    username = Console.ReadLine().Trim();
                }
                else if (Equals(password, ""))
                {
                    Console.Write("账号密码不得为空!\n请输入账号密码:");
                    password = Console.ReadLine().Trim();
                }
                else if (reader.Read())
                {
                    string result = reader.GetString(reader.GetOrdinal("password"));
                    if (MD5Encrypt(password, username).Equals(result))
                    {
                        Del(username);   //调用方法,删除注销后的账号信息
                        conn.Close();   //关闭数据库对象连接
                    }
                    else
                    {
                        Console.WriteLine("账号密码错误!");
                        Delete();
                    }
                }
                else
                {
                    YesOrNo();
                }
                conn.Close();
            }
        }

        private void Del(string username)    //数据库删除注销后的账号信息
        {
            SqlConnection conn = new SqlConnection(Stu);
            conn.Open();
            try
            {
                Console.WriteLine("账号注销成功!");
                string sql2 = "delete from 登录注册表 where username='" + username + "'";
                SqlCommand cmd1 = new SqlCommand(sql2, conn);
                cmd1.ExecuteNonQuery();
                conn.Close();
                Main2();
            }
            catch (Exception ex)
            {
                Console.WriteLine("账号注销失败!");
                Console.WriteLine(ex.Message);
                Main2();
            }
        }

        public void Main2()
        {
            Console.WriteLine("");
            Console.WriteLine("**************************");
            Console.WriteLine("******* 1.账号登录 *******");
            Console.WriteLine("******* 2.账号注册 *******");
            Console.WriteLine("******* 3.修改密码 *******");
            Console.WriteLine("******* 4.账号注销 *******");
            Console.WriteLine("******* 0.退出程序 *******");
            Console.WriteLine("**************************");
            Console.Write("请输入选择:");
            string num = Console.ReadLine().Trim().Trim();
            while (true)
            {
                switch (num)
                {
                    case "1": Login(); break;
                    case "2": Register(); break;
                    case "3": Change(); break;
                    case "4": Delete(); break;
                    case "0":
                        {
                            Console.WriteLine("程序已退出!");
                            Console.ReadKey();
                            Process.GetCurrentProcess().Kill();
                        }; break;
                    default:
                        {
                            Console.Write("请重新输入选择:");
                            num = Console.ReadLine().Trim();
                        }; break;
                }
            }
        }
    }

    //######################################################################################################
    //######################################################################################################
    //######################################################################################################


    class Grade
    {
        static readonly string Stu = ConfigurationManager.ConnectionStrings["sqlserver"].ConnectionString;     //设置数据库连接对象
        public void GradeTable()    //学生成绩管理系统
        {
            Console.WriteLine();
            Console.WriteLine("******************************");
            Console.WriteLine("******* 1.学生成绩输入 *******");
            Console.WriteLine("******* 2.学生成绩输出 *******");
            Console.WriteLine("******* 3.学生成绩查询 *******");
            Console.WriteLine("******* 4.学生成绩修改 *******");
            Console.WriteLine("******* 5.学生成绩删除 *******");
            Console.WriteLine("******* 6.返回登录界面 *******");
            Console.WriteLine("******* 0.退出当前程序 *******");
            Console.WriteLine("******************************");
            Console.Write("请输入选择:");

            string num = Console.ReadLine().Trim();
            while (true)
            {
                switch (num)
                {
                    case "1": GradeInput(); break;
                    case "2": GradeOutput(); break;
                    case "3": GradeFind(); break;
                    case "4": GradeChange(); break;
                    case "5": GradeDelete(); break;
                    case "6":
                        {
                            Account st = new Account();
                            st.Main2();
                        }
                        ; break;
                    case "0":
                        {
                            Console.WriteLine("程序已退出!");
                            Console.ReadKey();
                            Process.GetCurrentProcess().Kill();
                        }; break;
                    default:
                        {
                            Console.WriteLine("请重新输入选择!");
                            GradeTable();
                        }; break;
                }
            }
        }

        //######################################################################################################

        private void GradeInput()        //学生成绩输入
        {
            SqlConnection conn = new SqlConnection(Stu);
            Console.WriteLine("\n----------- 1.学生成绩输入 -----------");
            Console.Write("请输入学生姓名:");
            string name = Console.ReadLine().Trim();
            Console.Write("请输入学生学号:");
            string number = Console.ReadLine().Trim();
            Console.Write("请输入语文成绩:");
            string chinese = Console.ReadLine().Trim();
            Console.Write("请输入数学成绩:");
            string math = Console.ReadLine().Trim();
            Console.Write("请输入英语成绩:");
            string english = Console.ReadLine().Trim();
            while (true)
            {
                if (Equals(name, ""))
                {
                    Console.Write("学生姓名不得为空!\n请输入学生姓名:");
                    name = Console.ReadLine().Trim();
                }
                else if (Equals(number, ""))
                {
                    Console.Write("学生学号不得为空!\n请输入学生学号:");
                    number = Console.ReadLine().Trim();
                }
                else if (Equals(chinese, ""))
                {
                    Console.Write("语文成绩不得为空!\n请输入语文成绩:");
                    chinese = Console.ReadLine().Trim();
                }
                else if (Equals(math, ""))
                {
                    Console.Write("数学成绩不得为空!\n请输入数学成绩:");
                    math = Console.ReadLine().Trim();
                }
                else if (Equals(english, ""))
                {
                    Console.Write("英语成绩不得为空!\n请输入英语成绩:");
                    english = Console.ReadLine().Trim();
                }
                else
                {
                    conn.Open();
                    string sql = "Select Number from 学生成绩表 where Number='" + number + "'";
                    SqlCommand cmd = new SqlCommand(sql, conn);      //判断该学生成绩信息是否已输入
                    cmd.CommandType = CommandType.Text;
                    SqlDataReader sdt = cmd.ExecuteReader();
                    switch (sdt.Read())
                    {
                        case true:
                            Console.WriteLine("该学生成绩信息已输入!");
                            GradeTable();
                            break;
                        default:
                            Input(name, number, chinese, math, english);
                            break;
                    }
                    conn.Close();
                }
            }
        }

        private void Input(string name, string number, string chinese, string math, string english)  //保存输入的成绩到数据库
        {
            SqlConnection conn = new SqlConnection(Stu);
            try
            {
                conn.Open();
                string InsertStr = string.Format("insert into 学生成绩表 values('{0}','{1}','{2}','{3}','{4}')", name, number, chinese, math, english);
                SqlCommand comm = conn.CreateCommand();
                comm.CommandText = InsertStr;
                SqlCommand mycom = new SqlCommand(InsertStr, conn);
                mycom.ExecuteNonQuery();
                Console.WriteLine("学生成绩输入成功!");
                conn.Close();
                Console.ReadKey();
                GradeTable();
            }
            catch (Exception ex)
            {
                Console.WriteLine("学生成绩输入失败!");
                Console.WriteLine(ex.Message);
                Console.ReadKey();
                GradeTable();
            }
            conn.Close();
        }

        //################################################################################################

        private void GradeOutput()       //学生成绩输出
        {
            Console.WriteLine("\n****************************** 2.学生成绩输出 ********************************");
            Console.WriteLine("------------------------------------------------------------------------------");
            Console.WriteLine("   姓名   |   学号   |   语文   |   数学   |   英语   |   总分   |   平均分   ");
            Console.WriteLine("------------------------------------------------------------------------------");
            SqlConnection conn = new SqlConnection(Stu);
            conn.Open();
            SqlCommand cmd = conn.CreateCommand();
            cmd.CommandText = "select* from 学生成绩表 ";
            SqlDataReader reader = cmd.ExecuteReader();
            while (reader.Read())
            {
                string name = reader["Name"].ToString();
                string number = reader["Number"].ToString();
                double chinese = reader.GetDouble(reader.GetOrdinal("Chinese"));
                double math = reader.GetDouble(reader.GetOrdinal("Math"));
                double english = reader.GetDouble(reader.GetOrdinal("English"));
                double sum = chinese + math + english;
                double aver = sum / 3.0;
                Console.WriteLine("   {0}   |   {1}   |    {2}    |    {3}    |    {4}    |   {5:F2}  |   {6:F2}  ", name, number, chinese, math, english, sum, aver);
                Console.WriteLine("------------------------------------------------------------------------------");
            }
            Console.ReadKey();
            GradeTable();
        }

        //###################################################################################################

        private void GradeFind()
        {
            Console.WriteLine("\n****************** 3.学生成绩查询 ********************");
            Console.Write("1、按姓名查询;2、按学号查询;0、返回\n请输入选择:");
            string num = Console.ReadLine().Trim();
            while (true)
            {
                switch (num)
                {
                    case "1":
                        {
                            Console.Write("请输入学生姓名:");
                            string name = Console.ReadLine().Trim();
                            SelectName(name);
                        }; break;
                    case "2":
                        {
                            Console.Write("请输入学生学号:");
                            string number = Console.ReadLine().Trim();
                            SelectNumber(number);
                        }; break;
                    case "0": GradeTable(); break;
                    default:
                        {
                            Console.Write("请重新输入选择:");
                            num = Console.ReadLine().Trim();
                        }; break;
                }
            }
        }

        private void SelectName(string Name) //按学生姓名查找成绩
        {
            SqlConnection conn = new SqlConnection(Stu);
            conn.Open();
            string sqlStr = "Select count(*) from 学生成绩表 where Name='" + Name + "'";
            SqlCommand sqlcmd = new SqlCommand(sqlStr, conn);
            object count = sqlcmd.ExecuteScalar();
            switch ((int)count)
            {
                case 0:
                    {
                        Console.WriteLine("查无此人!");
                        Console.ReadKey();
                        GradeTable();
                    }; break;
                case 1:
                    {
                        SelectNameShow(Name);
                        conn.Close();
                    }; break;
                default:
                    {
                        Console.WriteLine("该学生姓名有多个,请通过学号来查询!");
                        GradeFind();
                    }; break;
            }
            conn.Close();
            GradeTable();
        }

        private void SelectNameShow(string Name)
        {
            SqlConnection conn = new SqlConnection(Stu);
            try
            {
                conn.Open();
                Console.WriteLine("------------------------------------------------------------------------------");
                Console.WriteLine("   姓名   |   学号   |   语文   |   数学   |   英语   |   总分   |   平均分   ");
                Console.WriteLine("------------------------------------------------------------------------------");
                SqlCommand cmd = conn.CreateCommand();
                cmd.CommandText = "select * from 学生成绩表 where Name= '" + Name + "'";
                SqlDataReader reader = cmd.ExecuteReader();
                if (reader.Read())
                {
                    string name = reader["Name"].ToString();
                    string number = reader["Number"].ToString();
                    double chinese = reader.GetDouble(reader.GetOrdinal("Chinese"));
                    double math = reader.GetDouble(reader.GetOrdinal("Math"));
                    double english = reader.GetDouble(reader.GetOrdinal("English"));
                    double sum = chinese + math + english;
                    double aver = sum / 3.0;
                    Console.WriteLine("   {0}   |   {1}   |    {2}    |    {3}    |    {4}    |   {5:F2}  |   {6:F2}  ", name, number, chinese, math, english, sum, aver);
                    Console.WriteLine("------------------------------------------------------------------------------");
                }
                Console.ReadKey();
                GradeTable();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                conn.Close();
                GradeTable();
            }
        }

        private void SelectNumber(string Number) //按学号查询成绩
        {
            SqlConnection conn = new SqlConnection(Stu);
            conn.Open();
            Console.WriteLine("------------------------------------------------------------------------------");
            Console.WriteLine("   姓名   |   学号   |   语文   |   数学   |   英语   |   总分   |   平均分   ");
            Console.WriteLine("------------------------------------------------------------------------------");
            SqlCommand cmd = conn.CreateCommand();
            cmd.CommandText = "select * from 学生成绩表 where Number= '" + Number + "'";
            SqlDataReader reader = cmd.ExecuteReader();
            if (reader.Read())
            {
                string name = reader["Name"].ToString();
                string number = reader["Number"].ToString();
                double chinese = reader.GetDouble(reader.GetOrdinal("Chinese"));
                double math = reader.GetDouble(reader.GetOrdinal("Math"));
                double english = reader.GetDouble(reader.GetOrdinal("English"));
                double sum = chinese + math + english;
                double aver = sum / 3.0;
                Console.WriteLine("   {0}   |   {1}   |    {2}    |    {3}    |    {4}    |   {5:F2}  |   {6:F2}  ", name, number, chinese, math, english, sum, aver);
                Console.WriteLine("------------------------------------------------------------------------------");
            }
            else
            {
                Console.WriteLine("查无此人!");
                Console.ReadKey();
                GradeFind();
            }
            conn.Close();
            Console.ReadKey();
            GradeTable();
        }

        //###################################################################################################

        private void GradeChange()   //学生成绩修改
        {
            Console.WriteLine("\n----------- 4.学生成绩修改 -----------");
            SqlConnection conn = new SqlConnection(Stu);
            conn.Open();
            Console.Write("请输入姓名:");
            string name = Console.ReadLine().Trim();
            Console.Write("请输入学号:");
            string number = Console.ReadLine().Trim();
            SqlCommand cmd = conn.CreateCommand();
            cmd.CommandText = "select * from 学生成绩表 where Name='" + name + "' and Number='" + number + "'";
            SqlDataReader sdt = cmd.ExecuteReader();
            while (true)
            {
                if (name.Equals(""))
                {
                    Console.WriteLine("姓名不得为空!\n请输入学生姓名:");
                    name = Console.ReadLine().Trim();
                }
                else if (Equals(number, ""))
                {
                    Console.Write("学号不得为空!\n请输入学生学号:");
                    number = Console.ReadLine().Trim();
                }
                else if (sdt.Read())
                {
                    AlterGrade(number);
                }
                else
                {
                    Console.WriteLine("查无此人!");
                    Console.ReadKey();
                    GradeChange();
                }
            }
        }

        private void AlterGrade(string number)    //选择要修改的课程科目
        {
            Console.Write("\n1、语文;2、数学;3、英语;0、返回\n请选择要修改成绩的学科:");
            string num = Console.ReadLine().Trim();
            while (true)
            {
                switch (num)
                {
                    case "1":
                        {
                            Console.Write("请输入修改后的语文成绩:");
                            string chinese = Console.ReadLine().Trim().Trim();
                            Alter(1, number, chinese);
                        }; break;
                    case "2":
                        {
                            Console.Write("请输入修改后的数学成绩:");
                            string math = Console.ReadLine().Trim().Trim();
                            Alter(2, number, math);
                        }; break;
                    case "3":
                        {
                            Console.Write("请输入修改后的英语成绩:");
                            string english = Console.ReadLine().Trim().Trim();
                            Alter(3, number, english);
                        }; break;
                    case "0": GradeTable(); break;
                    default:
                        {
                            Console.Write("请重新输入选择:");
                            num = Console.ReadLine().Trim();
                        }; break;
                }
            }
        }

        private void Alter(int num, string number, string item)    //
        {
            SqlConnection conn = new SqlConnection(Stu);
            conn.Open();
            if (num.Equals(1))
            {
                try
                {
                    string InsertStr = string.Format("update 学生成绩表 set Chinese='{0}' WHERE Number='{1}';", item, number);
                    SqlCommand comm = conn.CreateCommand();
                    SqlCommand mycom = new SqlCommand(InsertStr, conn);
                    mycom.ExecuteNonQuery();
                    conn.Close();
                    Console.WriteLine("语文成绩修改成功!");
                    Console.ReadKey();
                    AlterGrade(number);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("成绩修改失败!");
                    Console.WriteLine(ex.Message);
                    conn.Close();
                }
            }

            else if (num.Equals(2))
            {
                try
                {
                    string InsertStr = string.Format("update 学生成绩表 set Math='{0}' WHERE Number='{1}';", item, number);
                    SqlCommand comm = conn.CreateCommand();
                    SqlCommand mycom = new SqlCommand(InsertStr, conn);
                    mycom.ExecuteNonQuery();
                    conn.Close();
                    Console.WriteLine("数学成绩修改成功!");
                    Console.ReadKey();
                    AlterGrade(number);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("成绩修改失败!");
                    Console.WriteLine(ex.Message);
                    conn.Close();
                }
            }
            else if (num.Equals(3))
            {
                try
                {
                    string InsertStr = string.Format("update 学生成绩表 set English='{0}' WHERE Number='{1}';", item, number);
                    SqlCommand comm = conn.CreateCommand();
                    SqlCommand mycom = new SqlCommand(InsertStr, conn);
                    mycom.ExecuteNonQuery();
                    conn.Close();
                    Console.WriteLine("英语成绩修改成功!");
                    Console.ReadKey();
                    AlterGrade(number);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("成绩修改失败!");
                    Console.WriteLine(ex.Message);
                    conn.Close();
                }
            }
            conn.Close();
        }

        //####################################################################################################

        private void GradeDelete()   //学生成绩删除
        {
            SqlConnection conn = new SqlConnection(Stu);
            conn.Open();
            Console.WriteLine("\n****************** 5.学生成绩删除 ********************");
            Console.Write("请输入学生姓名:");
            string name = Console.ReadLine().Trim();
            Console.Write("请输入学生学号:");
            string number = Console.ReadLine().Trim();
            SqlCommand cmd = conn.CreateCommand();
            cmd.CommandText = "select * from 学生成绩表 where Name='" + name + "' and Number='" + number + "'";
            SqlDataReader reader = cmd.ExecuteReader();
            while (true)
            {
                if (Equals(name, ""))
                {
                    Console.Write("姓名不得为空!\n请输入学生姓名:");
                    name = Console.ReadLine().Trim();
                }
                else if (number.Equals(""))
                {
                    Console.Write("学号不得为空!\n请输入学生学号:");
                    number = Console.ReadLine().Trim();
                }
                else if (reader.Read())
                {
                    DelGrade(number);
                }
                else
                {
                    Console.WriteLine("查无此人!");
                    conn.Close();
                    GradeTable();
                }
            }
        }

        private void DelGrade(string number)
        {
            SqlConnection conn = new SqlConnection(Stu);
            conn.Open();
            try
            {
                string sql2 = "delete from 登录注册表 where username='" + number + "'";
                SqlCommand cmd1 = new SqlCommand(sql2, conn);
                cmd1.ExecuteNonQuery();
                Console.WriteLine("成绩信息删除成功!");
                conn.Close();
                Console.ReadKey();
                GradeTable();
            }
            catch (Exception ex)
            {
                Console.WriteLine("成绩信息删除失败!");
                Console.WriteLine(ex.Message);
                conn.Close();
                GradeTable();
            }
        }
    }


    //######################################################################################################
    //######################################################################################################
    //######################################################################################################


    class Program
    {
        static void Main()
        {
            Account st = new Account();
            st.Main2();

        }
    }
}




运行效果截图

C#连接SQL Server数据库实现简易的学生成绩管理系统_第6张图片


C#连接SQL Server数据库实现简易的学生成绩管理系统_第7张图片

总结

以上就是关于这个程序的全部了,感兴趣的小伙伴们可以来看看,供大家参考和学习可能还有不足之处,一些冗长的部分可以简化,也欢迎大家来批评指正。之前我还做了一个账号登录的窗体程序:C#窗体程序连接SQL Server实现账号登录、账号注册、修改密码、账号注销等功能。

你可能感兴趣的:(数据库,c#,sqlserver)