Detailed examples and code three Login

First, examples:

Now there is a point system, students log on each time receive 10 bonus points.

This example is just a simple three-login every time you log on success plus 10, and not other features, of course, there are many bug which may need to be optimized.

1. Design database tables:

Here Insert Picture Description

2. Data block diagram:

Here Insert Picture Description
Careful readers will certainly find that in addition to the UI, BLL, DAL three and a Model exist, the Model does not belong to any one, but three in order to better link exists. This class only stores, with more than three things in common use. Play a coordinating role. Model class, which is the entity class Entity.

3. several levels of relationships:

Here Insert Picture Description

Second, the source code analysis

Model class: to encapsulated data, for the data transfer between the three layers, without any reference to an assembly, but the other three all references to him

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Login.Model//是为了封装数据的,为了在三层之间传输数据,不会引用任何一个程序集,但是其他三个都引用他
{
   public  class UserInfo
    {
        public int Id { get; set; }
        public string UserName { get; set; }
        public string Password { get; set; }
        public string Email { get; set; }

    }
}

UI layer: Log

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;//Windows.Froms的命令空间

namespace LoginUI
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            //初始化窗体上的所有控件
            InitializeComponent();
        }

        private void btnLogin_Click(object sender, EventArgs e)
        {
           
            //获得登录窗体的用户名 Trim去空格操作,注意和VB的形式不一样
            string userName = txtUserName.Text.Trim();

            //因为密码中可能是空格所以不用去空格操作
            string password = txtpassword.Text;

            //实例化业务逻辑层的对象mgr,让业务逻辑层去判断输入内容
            Login.BLL.LoginManager mgr = new Login.BLL.LoginManager();

            //用户输入的内容通过mgr调用业务逻辑层的UserLogin方法,属于拿来主义。B层会去调用D层
            mgr.UserLogin(userName, password);

            //和Model 交互,将数据层的信息传入Model
            Login.Model.UserInfo user = mgr.UserLogin(userName ,password );

            //登录成功提示登录成功
            MessageBox.Show("登录用户:"+userName );

        }
    }
} 

Note: the UI code (layer B and layer D also) involve interaction with the B layer, and the layer interacts with the Model, the code is expressed as: Login.BLL.LoginManager and Login.Model.UserInfo, here discussed points:
Why write the class name + namespace? namespace references come directly can you use using?
Here Insert Picture Description
A: The introduction of direct namespace is possible, and directly after the introduction of the namespace, all related to these two types of objects, do not write their name + class name space, and thus embodies the idea of a reusable, not every times are written namespace.

This is the interaction between class and class, the library needs to cross a path problem when looking for class, first find the location where the class, find a class name. Of course, we are at the same level (with a library), call the objects of different classes, you do not go first path (no need to write namespace), it's like we find different files in the same file, their path all the same, we do not need to look for the path.
Here Insert Picture Description
Layer B:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Login.BLL//业务逻辑层:要与数据访问层交互,去调数据库,从而判断用户输入的账户密码是否数据库中存在
{
    public class LoginManager//登录管理
    {
        //定义一个方法UserLogin,返回值是Login.Model.UserInfo类型的对象
        public Login.Model.UserInfo UserLogin(string userName,string password)
        {
            
            //先实例化一个D层的对象
            Login.DAL.UserDAO uDao = new Login.DAL.UserDAO();

            //通过UI中填写的内容,调用SelectUser方法,返回相应的数据
            Login.Model.UserInfo user =uDao.SelectUser(userName ,password );//返回了user,含数据库中的内容

            if(user!=null)//登录成功
            {
                //登录成功,便给此用户加10分,并且返回user
                //与D层交互,实例化D层 一个加分对象
                Login.DAL.ScoreDAO sDao = new Login.DAL.ScoreDAO();
                //调用加分方法,加10分
                sDao.UpdateScore(userName, 10);
                return user;
            }
            else //若数据库中没有该用户名,则登录失败
            {
                throw new Exception("登录失败");
            }
        }
    }
}

Layer D: three categories:

class DbUtil: connect to the server to save the SQL statement
class UserDAO: access to the database - Add Score: insert statement
class ScoreDAO: access to the database - User Information: query

class DbUtil:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Login.DAL
{
    class DbUtil//用于保存 链接服务器的SQL语句
    {
        public static string ConnString = @"Server=DESKTOP-4LVQ49K;Database=Login;uid=sa;Password=123456";

    }
}

A question: D layer in this category DbUtil what's the use? Why write a separate category?

A: You can easily find: the function of this class is to achieve a connection to the database, but the database connection statement is very long, and UserDAO class and ScoreDAO class needs to connect to the database, so here the statement to connect the database to extract when packaged as a class, receiving ConnString a string type objects, then tied to a database, only need to call the object can!

class UserDAO:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Login.Model;
using System.Data;
using System.Data.SqlClient;//SqlConnection的命名空间

namespace Login.DAL
{
    public class UserDAO//数据访问层---访问用户信息
    {
        public Login.Model.UserInfo SelectUser(string userName, string password)
        {   //using 是为了自动释放()里边的资源
          using (SqlConnection conn = new SqlConnection(DbUtil.ConnString))//实例化了一个连接数据库的对象,类似于一个开数据库的钥匙
          {
                SqlCommand cmd = conn.CreateCommand();//在现有连接conn的基础上,创建一个命令用以执行SQL指令。
                conn.Open();//连接(数据库的)打开

                //	CommandText:获取或设置要在数据源中执行的 Transact-SQL 语句、表名或存储过程。
                cmd.CommandText = @"SELECT ID,UserName,Password,Email FROM USERS WHERE UserName=@UserName AND Password=@Password";//执行的select语句

                //CommandType:获取或设置一个值,该值指示解释 CommandText 属性的方式。
                cmd.CommandType = CommandType.Text;//CommandType是一个枚举类型,有三个值:text、StoredProcedure(存储过程)、TableDirect用于表示SqlCommand对象CommandType的执行形式,这里是text

                //把用户输入的内容存到Parameters集合中
                cmd.Parameters.Add(new SqlParameter("@UserName", userName));
                cmd.Parameters.Add(new SqlParameter ("@Password",password ));

                SqlDataReader reader = cmd.ExecuteReader();//ExecuteReader :尽可能快地对数据库进行查询并得到结果。

                //声明一个Login.Model.UserInfo 类型的对象user,只是声明
                Login.Model.UserInfo user = null;
              
               while (reader.Read())//把数据库中读到的信息给user对象,返回给B层
                {
                    if (user == null)
                    {
                        user = new Login.Model.UserInfo();//实例化user
                    }
                    user.Id = reader.GetInt32(0);
                    user.UserName = reader.GetString(1);
                    user.Password = reader.GetString(2);//not suggestion
                    if (!reader.IsDBNull(3))
                    {
                        user.Email = reader.GetString(3);
                    }

                }
                return user;
            }
            

        }
    }
}

class ScoreDAO:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
namespace Login.DAL
{
    public class ScoreDAO
    {
        public void UpdateScore(string userName, int value)
        {
            using (SqlConnection conn = new SqlConnection(DbUtil.ConnString))
            {
                SqlCommand cmd = conn.CreateCommand();
				conn.Open();
				
                cmd.CommandText = @"INSERT INTO SCORES(UserName,Score) Values(@UserName,@Score)";//插入积分
                
				//把用户输入的内容存到Parameters集合中
                cmd.Parameters.Add(new SqlParameter("@UserName", userName));

                cmd.Parameters.Add(new SqlParameter("@Score", value));
                //SqlCommand.ExecuteNonQuery()方法:对连接执行SQL语句并返回受影响的行数。
                cmd.ExecuteNonQuery();
            }
        }

    }
   
}

A question three issues:
✦ a problem: using () {} Usage:

using (SqlConnection conn = new SqlConnection(DbUtil.ConnString))
{
...
}

For a detailed explanation of this issue, see the next blog Xiao Bian:
https://blog.csdn.net/Ginny97/article/details/103943672

✦ Second problem: System.data and System.Data.Sqlclient namespace:

System.data: it means that there is a need to use the namespace at your data, place the array, the array type can be used directly, without the need to add a prefix.
The most common place should be ADO.NET data layer (ie class operation of the database)

System.Data.Sqlclient: redistributes ado.net assemblies Microsoft released sqlserver database in your code, after the introduction, you can use the SqlConnection, SqlCommand and other database objects to access sqlserver database.

✦ Question three: Understanding of cmd.Parameters.Add () is:
SqlParameter What is: It represents the SqlCommand parameter, and an optional mapping to DataSet columns. This class can not be inherited. (SqlCommand: To represent this class can not be inherited for Transact-SQL statements or stored procedures SQL Server database executed .DataSet:.. Represents the data cache memory)

Specific role and use, you can refer to the blogger's blog: thanks to her share, but also to learn a small series: https://blog.csdn.net/hsm_Jasmine/article/details/103339498

Well, for three small series of temporary learning to understand here, the next stop, seven reconstructed go from room! .◕‿◕.

Published 72 original articles · won praise 17 · views 10000 +

Guess you like

Origin blog.csdn.net/Ginny97/article/details/103985243