How to realize the login function in C#

How to write a login function

1. Preparation

Create a new database StudentDB

-- 使用master 数据库
use master
go
if exists(select *from sysdatabases where name='StudentDB')
drop database StudentDB
go
create database StudentDB
go

Create three new tables in StudentDB

use StudentDB
go

-- 新建学生表
if exists (select *from sysobjects where name='Student')
drop table Student
go
create table Student
(
stuId   int primary key identity(2000,1),
stuName varchar(30) not null,
stuSex  char(2) not null,
stuAge  int not null,
stuTel  varchar(11) not null,
stuPWd  varchar(30) not null
)

-- 添加学生表的数据
insert into Student (stuName,stuSex,stuAge,stuTel,stuPWd)values('张三','男',21,'12345678543','123456')
insert into Student (stuName,stuSex,stuAge,stuTel,stuPWd)values('赵六','男',21,'12345678543','123456')
insert into Student (stuName,stuSex,stuAge,stuTel,stuPWd)values('韩菲','女',20,'12345678543','123456')


 -- 新建教师表
if exists (select *from sysobjects where name='Teacher')
drop table Teacher
go
create table Teacher
(
tId   int primary key identity(4000,1),
tName varchar(30) not null,
tSex  char(2) not null,
tAge  int not null,
tTel  varchar(11) not null,
tTitle varchar(20),
tPwd   varchar(30) not null    
)
--添加教师表
insert into Teacher(tName,tSex,tAge,tTel,tTitle,tPwd)values('xx','男',32,'12345678901','副教授','123456')

 -- 新建管理员
if exists (select *from sysobjects where name='Admin')
drop table Admin
go
create table Admin
(
adminId   int primary key identity(4000,1),
adminName varchar(30) not null,
adminPWd  varchar(30) not null
)
-- 添加管理员表
insert into Admin(adminName,adminPwd) values('admin','123456')


Create a new winform project, modify the text box name to txtUserName, txtPwd; the login button name to btnLogin, btnExit.

Insert picture description here

2. Realize login

Function realization analysis

  • When the user clicks to log in, the program first determines whether the user name and password are empty, and then determines which role is to log in based on the value of the radio button.
  • After the above things are done, we need to compare the username and password to the database. First use the user name as the query condition, and return a user object (administrator, student, teacher, according to the specific situation, because we use the primary key as the user name, the primary key can distinguish a user, so the user name query only returns A piece of data). Determine whether the object is null, if it is null, it means that the user does not exist. Otherwise, judge whether the password is correct.

Prepare the entity class

Create three new classes in the project, the class name is the same as the table name, and the field name is the same as the field name in the table.

To add a class, select the item -> add -> class

Administrator

 public  class Admin
  {
        public int adminId { get; set; }
        public String adminName { get; set; }
        public String adminPwd { get; set; }
  }

Student class

public class Student
    {
        public int stuId { get; set; }
        public string stuName { get; set; }
        public string stuSex { get; set; }
        public int stuAge { get; set; }
        public string stuTel { get; set; }
        public string stuPwd { get; set; }


    }

Teacher class

 public class Teacher
 {
        public int tId { get; set; }
        public string tName { get; set; }
        public string tSex { get; set; }
        public int tAge { get; set; }
        public string tTel { get; set; }
        public string tTitle { get; set; }
        public string tPWd { get; set; }
 }

Prepare the DBHelper class

public class DbHelper
    {
        /// <summary>
        /// 获取连接对象
        /// </summary>
        /// <returns></returns>
        public static SqlConnection GetConnection()
        {

            SqlConnection conn = null;
            try
            {
                //可能发生错误的代码
                if (conn == null)
                {
                    conn = new SqlConnection();
                    conn.ConnectionString = ConfigurationManager.ConnectionStrings["connString"].ToString();
                    conn.Open();
                    conn.Close();
                }
                return conn;
            }
            catch (Exception ex)
            {
                //发生异常以后要做的事情
                throw ex; // 把问题抛出,让程序员知道那里出了错误
            }
        }

        /// <summary>
        /// 执行增删改
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public static int GetExcuet(string sql)
        {
            // 1. 获取连接对象
            SqlConnection conn = GetConnection();
            try
            {
                // 2.打开链接
                conn.Open();
                //3.创建SqlCommand对象,sql语句,连接对象
                SqlCommand cmd = new SqlCommand(sql, conn);
                // 4.执行SQL,并返回受影响的行数
                return cmd.ExecuteNonQuery(); ;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                conn.Close();
                conn.Dispose();
            }
        }

        /// <summary>
        /// 返回执行查询的结果
        /// </summary>
        /// <returns></returns>
        public static DataTable GetDataSet(String sql)
        {
            try
            {
                // 1.获取链接对象
                SqlConnection conn = GetConnection();
                //2.创建适配器对象
                SqlDataAdapter da = new SqlDataAdapter(sql, conn);
                //3.创建DataSet 对象
                DataSet ds = new DataSet();
                da.Fill(ds);
                return ds.Tables[0];
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
       
      
    }

Add the database connection string in App.config and add it under the configuration tab

<connectionStrings>
    <add name="connString" connectionString="Data Source=.;Initial Catalog=StudentDB;Persist Security Info=True;User ID=sa;Password=123456"/>
  </connectionStrings>

Implement click events

When the user clicks, we will execute the login event

According to our analysis, we must first determine whether the user and password are correct

           //获取用户名和密码
            string username = txtUserName.Text.Trim();
            string pwd = txtPwd.Text.Trim();
            //当用户名为空的时候就不往下面执行了
            if (username.Equals(""))
            {
                MessageBox.Show("用户名不能为空");
                return;
            }
            if (pwd.Equals(""))
            {
                MessageBox.Show("密码不能为空");
                return;
            }

After judging all the public issues, then we have to judge which user logged in. We can judge by the checked attribute of the radio button, and then call their login methods respectively.

           //管理员登录
            if (radAdmin.Checked)
            {
                AdminLogin(username);
            }
            //学生登录
            if (radStudent.Checked)
            {
               StudentLogin();
            }
            //教师登录
            if (radTeacher.Checked)
            {
                TeacherLogin();
            }

The administrator login method is implemented. The query is performed according to the administrator's user name, and the number of rows in the returned table is judged. If the number of rows is less than 1, then the user does not exist, and null is returned, otherwise an administrator object is returned. Other similar

  private Admin AdminLogin(String username)
        {

            string sql = string.Format("select *from Admin where adminId={0}",username);
            DataTable table=  DbHelper.GetDataSet(sql);
            //判断表的行数,大于等于1表示有数据,用户存在,否则返回null
            if (table.Rows.Count < 1) return null;

            //新建一个admin对象
            Admin admin = new Admin();
            admin.adminId = Convert.ToInt32(table.Rows[0]["adminId"]);
            admin.adminName = table.Rows[0]["adminName"].ToString();
            admin.adminPwd = table.Rows[0]["adminPwd"].ToString();
            return admin;
        }

Student login method

 private Student StudentLogin(string username)
        {
            string sql = string.Format("select *from Student where stuId={0}", username);
            DataTable table = DbHelper.GetDataSet(sql);
            //判断表的行数,大于等于1表示有数据,用户存在,否则返回null
            if (table.Rows.Count < 1) return null;

            /*新建一个student对象 ,这里只给了三个字段进行了赋值,
             * 因为我们登录的时候,只用到了id和密码,
             * 其他时候根据需求进行赋值
            */
            Student student = new Student();
            student.stuId = Convert.ToInt32(table.Rows[0]["stuId"]);
            student.stuName = table.Rows[0]["stuName"].ToString();
            student.stuPwd = table.Rows[0]["stuPwd"].ToString();
            return student;
        }

Teacher login method

  private Teacher TeacherLogin(string username)
        {
            string sql = string.Format("select *from Teacher where tId={0}", username);
            DataTable table = DbHelper.GetDataSet(sql);
            //判断表的行数,大于等于1表示有数据,用户存在,否则返回null
            if (table.Rows.Count < 1) return null;

            /*新建一个student对象 ,这里只给了三个字段进行了赋值,
             * 因为我们登录的时候,只用到了id和密码,
             * 其他时候根据需求进行赋值
            */
            Teacher teacher = new Teacher();
            teacher.tId = Convert.ToInt32(table.Rows[0]["tId"]);
            teacher.tName = table.Rows[0]["tName"].ToString();
            teacher.tPWd = table.Rows[0]["tPWd"].ToString();
            return teacher;
        }

After the login method is completed, I need to process the returned result. First judge whether the object is null, if it is null, it means that the user does not exist. On the contrary, the passwords of the objects are compared. If the password is correct, the login is successful, and if the password is incorrect, the password is incorrect.

 private void btnLogin_Click(object sender, EventArgs e)
   {
       //获取用户名和密码
       string username = txtUserName.Text.Trim();
       string pwd = txtPwd.Text.Trim();
       if (username.Equals(""))
       {
           MessageBox.Show("用户名不能为空");
           return;
       }
       if (pwd.Equals(""))
       {
           MessageBox.Show("密码不能为空");
           return;
       }
       //管理员登录
       if (radAdmin.Checked)
       {
           /*为什么要返回来,因为以后处理逻辑可能在不同类里面,
            * 这里只是模拟进行分层操作*/
          Admin admin=  AdminLogin(username);
          if (admin == null)
          {
               MessageBox.Show("用户不存在");
               return;
           }
          if (!admin.adminPwd.Equals(pwd))
          {
               MessageBox.Show("密码错误");
               return;
          }
     
       }
       //学生登录
       if (radStudent.Checked)
       {
           Student  student= StudentLogin(username);
           if (student == null)
           {
               MessageBox.Show("用户不存在");
               return;
           }
           if (!student.stuPwd.Equals(pwd))
           {
               MessageBox.Show("密码错误");
               return;
           }
       }
       //教师登录
       if (radTeacher.Checked)
       {
           Teacher teacher=  TeacherLogin(username);

           if (teacher == null)
           {
               MessageBox.Show("用户不存在");
               return;
           }
           if (!teacher.tPWd.Equals(pwd))
           {
               MessageBox.Show("密码错误");
               return;
           }
       }

       MessageBox.Show("登录成功");
   }

to sum up

  1. In login, we first determine the public conditions, such as the user name, password is empty, etc., clever use of return, so that the logic of the entire code becomes simple.
  2. After judging the common conditions, make judgments for each specific role.
  3. Use the user name to query and determine the number of rows in the returned table. If the number of rows is less than 1, then the user does not exist, otherwise an object is instantiated and assigned to the object
  4. Determine whether the returned object is empty, if it is empty, the user does not exist, otherwise the user exists
  5. Finally, the password is judged. If the password is correct, the login is successful. If the password is incorrect, a prompt that the password is incorrect will pop up.
  6. Project download address: https://download.csdn.net/download/golden_stone_fish/19405141