数据库实验4:稍微复杂的设计页面(MD5)(c#)

废话不多说,我们现在开始,老生常谈的话题建立项目以及设计初始化的页面我就不说了,详细不会了解之前博客,我们先放出来页面的设计。
登录页面:
数据库实验4:稍微复杂的设计页面(MD5)(c#)_第1张图片注册页面:
数据库实验4:稍微复杂的设计页面(MD5)(c#)_第2张图片
主页面:
数据库实验4:稍微复杂的设计页面(MD5)(c#)_第3张图片首先我们先来运行一波
先注册
数据库实验4:稍微复杂的设计页面(MD5)(c#)_第4张图片注册
数据库实验4:稍微复杂的设计页面(MD5)(c#)_第5张图片数据库实验4:稍微复杂的设计页面(MD5)(c#)_第6张图片登录
数据库实验4:稍微复杂的设计页面(MD5)(c#)_第7张图片数据库实验4:稍微复杂的设计页面(MD5)(c#)_第8张图片主页面
数据库实验4:稍微复杂的设计页面(MD5)(c#)_第9张图片按refresh
数据库实验4:稍微复杂的设计页面(MD5)(c#)_第10张图片按Show photo
数据库实验4:稍微复杂的设计页面(MD5)(c#)_第11张图片开始我们的代码篇
首先,因为我们这个体系是跟数据库相连接的,所以我们要定义一个数据库

--Edit by David @ HeBei University 2019

DROP DATABASE IF EXISTS curricula_variable_system;  

CREATE DATABASE curricula_variable_system;  

USE curricula_variable_system;

DROP TABLE IF EXISTS SC
DROP TABLE IF EXISTS Student
DROP TABLE IF EXISTS Course
DROP TABLE IF EXISTS SysUser
DROP TABLE IF EXISTS SysLog

CREATE TABLE SysUser          
 (	
 UserID NCHAR(20) PRIMARY KEY,                          
 UserPassWord NCHAR(32) ,             
 UserSchoolID NCHAR(20),
 UserMobile NCHAR(11),
 UserBirthday datetime,
 UserIdentity NCHAR(20),
 UserPhoto image
 ); 


 CREATE TABLE SysLog          
 (	
 UserID NCHAR(20) ,                          
 DateAndTime datetime,
 UserOperation NCHAR(200)
 ); 

CREATE TABLE Student          
 (	
 Sno CHAR(9) PRIMARY KEY,        /* 列级完整性约束条件,Sno是主码*/                  
 Sname CHAR(20) UNIQUE,             /* Sname取唯一值*/
 Ssex CHAR(2),
 Sage SMALLINT,
 Sdept CHAR(20)
 ); 

CREATE TABLE  Course
 (	
 Cno CHAR(4) PRIMARY KEY,
 Cname CHAR(40),            
 Cpno CHAR(4),               	                      
 Ccredit SMALLINT,
 FOREIGN KEY (Cpno) REFERENCES  Course(Cno) 
 ); 

CREATE TABLE  SC
 (
 Sno CHAR(9), 
 Cno CHAR(4),  
 Grade SMALLINT,
 PRIMARY KEY (Sno,Cno),                     /* 主码由两个属性构成,必须作为表级完整性进行定义*/
 FOREIGN KEY (Sno) REFERENCES Student(Sno),  /* 表级完整性约束条件,Sno是外码,被参照表是Student */
 FOREIGN KEY (Cno)REFERENCES Course(Cno)     /* 表级完整性约束条件, Cno是外码,被参照表是Course*/
 ); 

INSERT  INTO  SysUser VALUES ('admin','123','000','13812345678',1999-1-1,'0',NULL);

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);

SELECT * FROM Student

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' 

SELECT * FROM Course

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);

SELECT * FROM SC



IF(OBJECT_ID('regist_recorder') is not null)        -- 判断名为 regist_recorder 的触发器是否存在
DROP TRIGGER regist_recorder        -- 删除触发器
GO

CREATE TRIGGER regist_recorder
ON SysUser  	         
AFTER
INSERT
AS 
	declare @UserName    nchar(20)
	declare @DateTime    datetime
	declare @UserOperation nchar(200)

	select @UserName = system_user
	select @DateTime = CONVERT(datetime,GETDATE(),120) 

	declare @op varchar(10)
	select @op=case when exists(select 1 from inserted) and exists(select 1 from deleted)
                   then 'Update'
                   when exists(select 1 from inserted) and not exists(select 1 from deleted)
                   then 'Insert'
                   when not exists(select 1 from inserted) and exists(select 1 from deleted)
                   then 'Delete' end
                   
	
	select @UserOperation = @op
	

	INSERT INTO SysLog(UserID,DateAndTime,UserOperation)
	VALUES (@UserName,@DateTime,@UserOperation)


定义好数据库,开始我们的代码篇
首先一个新的知识,关于鼠标离开这个文本框,我们定义格式是否与我们相同,我们定义提醒框是,函数是在这里找,点击文本框,右边的属性中找Leave,点击,会出现在函数中
数据库实验4:稍微复杂的设计页面(MD5)(c#)_第12张图片首先登陆页面

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.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Resgister_Login
{
    public partial class login : Form
    {
        public login()
        {
            InitializeComponent();
        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)  //转化页面
        {
            resgister res = new resgister();
            res.ShowDialog();
        }
        public string code;

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

            if (username == "admin")
                password = "123";//测试用例,便于初始化时候的 admin 密码 123可以顺利登陆。程序完成后可注释掉这行代码。

            //string connstr = ConfigurationManager.ConnectionStrings["connectionString"].ToString(); //读取连接字符串
            string myConnString = "Data Source=.;Initial Catalog=curricula_variable_system;Persist Security Info=True;User ID=sa;Password=******";

            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 && textBox3.Text == code)
            {
                MessageBox.Show("欢迎使用!");             //登录成功
                Main form2 = new Main();
                form2.Show();
                this.Hide();
            }
            else
            {
                MessageBox.Show("登录失败!");
                return;
            }
            sqlDataReader.Close();
            sql = "insert into SysLog values ( '" + username + "' , '" + DateTime.Now + "' , '" + "Login" + "')";                                            //编写SQL命令
            sqlCommand = new SqlCommand(sql, sqlConnection);
            sqlCommand.ExecuteNonQuery();
            sqlConnection.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 button2_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void label5_Click(object sender, EventArgs e)
        {

        }

        private void login_Load_1(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();
            }

            label5.Text = code;
        }

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

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

注册

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;
using System.IO;
using System.Security.Cryptography;

namespace Resgister_Login
{
    public partial class resgister : Form
    {
        public resgister()
        {
            InitializeComponent();
        }

        private void label2_Click(object sender, EventArgs e)
        {

        }

        private void label5_Click(object sender, EventArgs e)
        {

        }

        private void label6_Click(object sender, EventArgs e)
        {

        }

        private void resgister_Load(object sender, EventArgs e)
        {

        }
        public Byte[] mybyte = new byte[0];
        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                string connString = "Data Source=.;Initial Catalog=curricula_variable_system;Persist Security Info=True;User ID=sa;Password=******";//数据库连接字符串
                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", textBox1.Text);
                command.Parameters.Add(sqlParameter);
                sqlParameter = new SqlParameter("@userpassword", EncryptWithMD5(textBox2.Text));
                command.Parameters.Add(sqlParameter);
                sqlParameter = new SqlParameter("@userschoolid", textBox3.Text);
                command.Parameters.Add(sqlParameter);
                sqlParameter = new SqlParameter("@usermobile", textBox4.Text);
                command.Parameters.Add(sqlParameter);
                sqlParameter = new SqlParameter("@userbirthday", 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);

                //打开数据库连接
                connection.Open();
                command.ExecuteNonQuery();
                connection.Close();
                MessageBox.Show("register succeed");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }


            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 button1_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 button3_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void resgister_FormClosed(object sender, FormClosedEventArgs e)
        {

        }

        private void button2_Leave(object sender, EventArgs e)
        {

        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }
    }
}

主页面

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.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Resgister_Login
{
    public partial class Main : Form
    {
        public Main()
        {
            InitializeComponent();
        }

        private void Main_Load(object sender, EventArgs e)
        {
            // TODO: 这行代码将数据加载到表“curricula_variable_systemDataSet14.SC”中。您可以根据需要移动或删除它。
            this.sCTableAdapter.Fill(this.curricula_variable_systemDataSet14.SC);
            // TODO: 这行代码将数据加载到表“curricula_variable_systemDataSet13.Course”中。您可以根据需要移动或删除它。
            this.courseTableAdapter.Fill(this.curricula_variable_systemDataSet13.Course);
            // TODO: 这行代码将数据加载到表“curricula_variable_systemDataSet12.Student”中。您可以根据需要移动或删除它。
            this.studentTableAdapter.Fill(this.curricula_variable_systemDataSet12.Student);
            // TODO: 这行代码将数据加载到表“curricula_variable_systemDataSet11.SysLog”中。您可以根据需要移动或删除它。
            this.sysLogTableAdapter.Fill(this.curricula_variable_systemDataSet11.SysLog);
            // TODO: 这行代码将数据加载到表“curricula_variable_systemDataSet.SysUser”中。您可以根据需要移动或删除它。
            this.sysUserTableAdapter.Fill(this.curricula_variable_systemDataSet.SysUser);

        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.sysLogTableAdapter.Fill(this.curricula_variable_systemDataSet11.SysLog);
        }

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

        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                string connString = "Data Source=.;Initial Catalog=curricula_variable_system;Persist Security Info=True;User ID=sa;Passwor=******";//数据库连接字符串
                SqlConnection connection = new SqlConnection(connString);//创建connection对象

                //打开数据库连接
                connection.Open();
                //创建SQL语句
                string sql = "select UserPhoto from SysUser where UserID = '" + textBox1.Text + "'";
                //创建SqlCommand对象
                SqlCommand command = new SqlCommand(sql, connection);
                //创建DataAdapter对象
                SqlDataAdapter dataAdapter = new SqlDataAdapter(command);
                //创建DataSet对象
                DataSet dataSet = new DataSet();
                dataAdapter.Fill(dataSet, "SysUser");
                int c = dataSet.Tables["SysUser"].Rows.Count;
                if (c > 0)
                {
                    Byte[] mybyte = new byte[0];
                    mybyte = (Byte[])(dataSet.Tables["SysUser"].Rows[c - 1]["UserPhoto"]);
                    MemoryStream ms = new MemoryStream(mybyte);
                    pictureBox1.Image = Image.FromStream(ms);
                }
                else
                    pictureBox1.Image = null;
                connection.Close();

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }
}

主要内容就是以上,说来也惭愧,周一讲的这些内容,被我用在周三的实验课上写,而且小毛病出现了不少,我用VS次数还是太少,我关了一些东西,我不知道从哪里打开,老师上课讲的直接点击数据源,向里面导表,也不知道我是之前关了,还是我没有,我找不到在哪里显示。我就一个一个导入表,导入表的时候,我的登陆表他只显示一列,不知道这是什么原因,最后原因没找到,又重新写了一遍,就在我以为所有的事情大功告成的时候,我再次运行的时候说我数据库没链接成功,我链接后,也不知道我是点击了哪里,我在SQL SERVER中建立的数据库没了,我说重新建的时候可能我之前没清理干净又说我不能减,我又视图关软件开软件,关机开机操作了一波,结果并没有什么卵用,最后用了DROP DATABASE 数据库名,删干净后又重新建立了一个,最后在写完一篇代码。
对于大作业,我还没有开始设想,可能会晚点,今天先到这里。

你可能感兴趣的:(数据库实验4:稍微复杂的设计页面(MD5)(c#))