实验反馈4

在学习了C#的基础知识后,本周正式开始大作业的设计过程。
这周新学习了设计注册信息、登录时的验证码、使用正则表达式对用户名和密码进行限制、对密码存储时使用MD5密码加密,增加了数据的可靠性。

本来以为这周可以基本把表的增删改查数据全部完成,但是中间由于系统原因出现了问题,耽误了好长时间,进度有点慢。一开始是在DataGridView连接数据源时出现“安装缺失的程序包”,点击【确定】后,不显示安装,只显示一些表,经过长时间的上网查询之后仍然无法解决,最后不得不把Visual Studio卸载重装。好在重装之后可以正常使用。
另外还出现了一个问题:就是在程序运行显示数据库中表的信息时显示“用户sa登录失败”,无法显示,检查之后并没有发现什么错误,后来重新建了一个项目,将之前的代码复制过去之后就莫名其妙的好了。

现在已经实现新用户的注册,登录界面,以管理员的身份登录完成对Student表的基本操作,对Course的操作。还剩下管理员对SC表的操作以及学生登录,还有模糊查询等细致化。

登录:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace dazuoye
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }


        public void ShowCode()   //验证码取值
        {
            labelcode.Text = "";
            //随机实例化 
            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();
            }

            labelcode.Text = code;

        }

        public string code;



        private void Form1_Load(object sender, EventArgs e)
        {
            ShowCode();
        }

        private void linkLabelregister_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Register register = new Register();
            register.ShowDialog();
        }

        private void linkLabelchange_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            this.code = "";
            ShowCode();
        }

        private void buttonclose_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void buttonlogin_Click(object sender, EventArgs e)
        {
            string username = textBoxusername.Text.Trim();  //取出账号
            string password = EncryptWithMD5(textBoxpassword.Text.Trim());  //取出密码并加密

            string myConnString = "Data Source =.; Initial Catalog = School;  Persist Security Info = True;User ID = sa; Password = 123";

            SqlConnection sqlConnection = new SqlConnection(myConnString);  //实例化连接对象
            sqlConnection.Open();

            string sql = "select UserID,UserPassword from SysUser where UserID = '" + username + "' and UserPassword = '" + password + "'";                                            //编写SQL命令
            SqlCommand sqlCommand = new SqlCommand(sql, sqlConnection);

            SqlDataReader sqlDataReader = sqlCommand.ExecuteReader();

            if (sqlDataReader.HasRows && textBoxcode.Text == code && radioButtonstudent.Checked)        //学生成功登录
            {
                MessageBox.Show("欢迎使用!");             //登录成功
                StudentMain studentmain = new StudentMain();
                studentmain.ShowDialog();
                //this.Hide();
            }
            if (sqlDataReader.HasRows && textBoxcode.Text == code && radioButtonadmin.Checked)      //管理员成功登录
            {
                MessageBox.Show("欢迎使用!");             //登录成功
                AdminMain adminmain = new AdminMain();
                adminmain.Show();
               // this.Hide();
            }
            if (textBoxcode.Text != code)       //验证码输入错误,登录失败
            {
                MessageBox.Show("验证码错误!");
            }
            if (!sqlDataReader.HasRows)         //用户名或密码错误,登录失败
            {
                MessageBox.Show("密码错误或该用户不存在!");
            }
            if (!radioButtonstudent.Checked && !radioButtonadmin.Checked)        //未选择身份
            {
                MessageBox.Show("请选择登录身份!");
            }
        }

        public static string EncryptWithMD5(string source)      //MD5加密
        {
            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();
        }
    }
}

新用户的注册:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace dazuoye
{
    public partial class Register : Form
    {
        public Register()
        {
            InitializeComponent();
        }


        public Byte[] mybyte = new byte[0];

        public static string EncryptWithMD5(string source)  //MD5加密
        {
            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 buttonphoto_Click(object sender, EventArgs e)
        {
            //打开浏览图片对话框
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.ShowDialog();
            string picturePath = openFileDialog.FileName;//获取图片路径
            //文件的名称,每次必须更换图片的名称,这里很为不便
            //创建FileStream对象
            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();
        }

        private void buttonok_Click(object sender, EventArgs e)
        {
            try
            {
                string connString = "Data Source =.; Initial Catalog = School;  Persist Security Info = True;User ID = sa; Password = 123";//数据库连接字符串
                SqlConnection connection = new SqlConnection(connString);//创建connection对象
                string sql = "insert into SysUser (UserID,   UserPassWord ,   UserSchoolID, UserMobile, UserBirthday , UserIdentity , UserPhoto ) " +
                                                        "values (@userid, @userpassword,@userschoolid,@usermobile,@userbirthday,@useridentity,@userphoto)";
                SqlCommand command = new SqlCommand(sql, connection);

                SqlParameter sqlParameter = new SqlParameter("@userid", textBoxusername.Text);
                command.Parameters.Add(sqlParameter);
                sqlParameter = new SqlParameter("@userpassword", EncryptWithMD5(textBoxpassword.Text));
                command.Parameters.Add(sqlParameter);
                sqlParameter = new SqlParameter("@userschoolid", textBoxid.Text);
                command.Parameters.Add(sqlParameter);
                sqlParameter = new SqlParameter("@usermobile", textBoxmobile.Text);
                command.Parameters.Add(sqlParameter);
                sqlParameter = new SqlParameter("@userbirthday", dateTimePickerbirth.Value);
                command.Parameters.Add(sqlParameter);
                sqlParameter = new SqlParameter("@useridentity", comboBoxidentity.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);

                //打开数据库连接
                connection.Open();
                command.ExecuteNonQuery();
                connection.Close();
                MessageBox.Show("注册成功!");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            this.Close();
        }

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

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

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

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

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

管理员对Student表的增删改查:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace dazuoye
{
    public partial class Admin_Student : Form
    {
        public Admin_Student()
        {
            InitializeComponent();
        }

        private void Admin_Student_Load(object sender, EventArgs e)
        {
            // TODO: 这行代码将数据加载到表“schoolDataSet.Student”中。您可以根据需要移动或删除它。
            this.studentTableAdapter.Fill(this.schoolDataSet.Student);

        }

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

        SqlConnection con = new SqlConnection("Data Source =.; Initial Catalog = School;  Persist Security Info = True;User ID = sa; Password = 123"); //连接数据库
      
        private void buttonadd_Click(object sender, EventArgs e)        //增加
        {
            string StuSno = textBoxsno.Text.Trim();
            string StuSname = textBoxsname.Text.Trim();
            string StuSsex = textBoxssex.Text.Trim();
           string  StuSage = textBoxsage.Text.Trim();
            string StuSdept = textBoxsdept.Text.Trim();
            //SqlConnection con = new SqlConnection("Data Source =.; Initial Catalog = Student;  Persist Security Info = True;User ID = sa; Password = 123"); //连接数据库
            try
            {
                con.Open();     //打开数据库
               //string insertStr= "INSERT INTO Student(Sno,Sname,Ssex,Sage,Sdept) " + "VALUES (@StuSno,@StuSname,@StuSsex,@StuSage,@StuSdept)";
                string insertStr = "INSERT INTO Student(Sno,Sname,Ssex,Sage,Sdept)" + "VALUES('" + StuSno + "','" + StuSname + "','" + StuSsex + "'," + StuSage + ",'" + StuSdept + "')";
                SqlCommand cmd = new SqlCommand(insertStr, con);
                cmd.ExecuteNonQuery();      //将增加后的信息直接出来
            }
            catch
            {
                if (StuSsex != "男" && StuSsex != "女")
                    MessageBox.Show("Ssex输入必须为“男”或“女”!");
                if (Convert.ToInt32(StuSage) <=0)
                    MessageBox.Show("请输入大于0的年龄值!");
                if (StuSno  =="")
                    MessageBox.Show("学号不能为空!");
               
               
            }
            finally
            {
                con.Dispose();      //关闭数据库
                con.Close();
            }
            this.studentTableAdapter.Fill(this.schoolDataSet.Student);
        }

        private void buttondelete_Click(object sender, EventArgs e)
        {
            try
            {
                con.Open();     //打开数据库
                string select_Sno = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();//选择的当前行第一列的值,也就是Sno
                string delete_by_Sno = "DELETE FROM Student WHERE Sno='" + select_Sno + "'";//sql删除语句
                SqlCommand cmd = new SqlCommand(delete_by_Sno, con);
                cmd.ExecuteNonQuery();      
            }
            catch
            {
                MessageBox.Show("请选择正确行!");
            }
            finally
            {
                con.Dispose();      //关闭数据库
            }
            this.studentTableAdapter.Fill(this.schoolDataSet.Student);
        }

        private void buttonchange_Click(object sender, EventArgs e)     //修改,根据学号修改其他内容
        {
            string StuSno = textBoxsno.Text.Trim();
            string StuSname = textBoxsname.Text.Trim();
            string StuSsex = textBoxssex.Text.Trim();
            string StuSage = textBoxsage.Text.Trim();
            string StuSdept = textBoxsdept.Text.Trim();
            try
            {
                con.Open();     //打开数据库
                string update_sname = "UPDATE Student SET Sname='" + StuSname + "'WHERE Sno='" + StuSno + "'";
                string update_sex = "UPDATE Studnet SET Ssex='" + StuSsex + "' WHERE Sno='" + StuSno + "'";
                string update_age = "UPDATE Studnet SET Sage='" + StuSage + "' WHERE Sno='" + StuSno + "'";
                string update_sdept = "UPDATE Studnet SET Sdept='" + StuSdept + "' WHERE Sno='" + StuSno + "'";

                SqlCommand cmd = new SqlCommand(update_sname, con);
                cmd.ExecuteNonQuery();      
            }
            catch
            {
                if (StuSsex != "男" && StuSsex != "女")
                    MessageBox.Show("Ssex输入必须为“男”或“女”!");
                if (Convert.ToInt32(StuSage) <= 0)
                    MessageBox.Show("请输入大于0的年龄值!");
                if (StuSno == "")
                    MessageBox.Show("学号不能为空!");
            }
            finally
            {
                con.Dispose();      //关闭数据库
            }
            this.studentTableAdapter.Fill(this.schoolDataSet.Student);
        }

        private void buttonselect_Click(object sender, EventArgs e)     //查找,根据学号查找
        {
            string StuSno = textBoxsno.Text.Trim();
            String conn = "Data Source =.; Initial Catalog = School;  Persist Security Info = True;User ID = sa; Password = 123";
            SqlConnection sqlconnection = new SqlConnection(conn);//实例化连接对象
            try
            {
                sqlconnection.Open();
                String select_by_sno = "select * from Student where Sno='" + StuSno + "'";
                SqlCommand sqlcommand = new SqlCommand(select_by_sno, sqlconnection);
                SqlDataReader sqldatareader = sqlcommand.ExecuteReader();
                BindingSource bindingsource = new BindingSource();
                bindingsource.DataSource = sqldatareader;
                dataGridView1.DataSource = bindingsource;
                //将读出来的值赋给数据源,再将数据源给dataGridView
            }
            catch
            {
                MessageBox.Show("查询语句有误,请认真检查SQL语句");
            }
            finally
            {
                sqlconnection.Close();
            }

        }
    }
}

登录界面:可以使用学生和管理员两种身份登录,验证码看不清楚是时可以刷新,换一张。

注册界面:

管理员对Student表的操作:

管理员对Course表操作:

这次的操作中间出现了较多的问题,出现了很多之前没有出现过的问题,下周要加快进度了!

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值