三层架构下实现用户登陆C#
上篇文章讲到三层。接下来就通过一个实例详细的看怎么用三层实现用户登陆界面。
一、Model实体(LoginModel):
namespace LoginModel { //加入类:UserInfo Model实体作用:封装数据,使数据在三层中传输 。更倾向于业务逻辑层 public class UserInfo { //定义用户属性 public int ID { get; set; } public string UserName { get; set; } public string Password { get; set; } } }二、UI层的设计:
首先简单的界面相信大家都会:
接下来是代码:
namespace LoginUI { public partial class frmLogin : Form { public frmLogin() { InitializeComponent(); } private void btnLogin_Click(object sender, EventArgs e) { //UI层将用户输入数据传递给BLL层 string userName = txtUserName.Text.Trim(); string password = txtPassword.Text; LoginBLL.LoginManager mgr = new LoginBLL.LoginManager(); LoginModel.UserInfo user = mgr.UserLogin(userName, password); //将UI层返回业务层传递的数据给用户 MessageBox.Show("登陆用户:" + user.UserName); } } }
三、BLL层代码
namespace LoginBLL { public class LoginManager { public LoginModel.UserInfo UserLogin(string userName, string password) { LoginDAL.UserDAO uDao = new LoginDAL.UserDAO();//实例化DAL层 LoginModel.UserInfo user = uDao.SelectUser(userName, password); //不需訪问数据源直接运行业务逻辑 if (user != null) { return user; } else { throw new Exception("登陆失败"); } } } }四、DAL层 代码
public class UserDAO { public LoginModel.UserInfo SelectUser(string userName, string Password) { //建立数据库连接 string ConnString = @"Server=192.168.24.154;DataBase=机房收费系统人员记录; User ID=sa; Password=123"; using (SqlConnection conn = new SqlConnection(ConnString)) { //运行SQL语句进行查询 SqlCommand cmd = conn.CreateCommand(); cmd.CommandText = @"SELECT ID,UserName,Password FROM UserInfo WHERE UserName=@UserName AND Password=@Password"; //输出查询结果 cmd.CommandType = CommandType.Text; //加入两个參数 cmd.Parameters.Add(new SqlParameter(@"UserName", userName)); cmd.Parameters.Add(new SqlParameter(@"Password", Password)); conn.Open(); SqlDataReader reader = cmd.ExecuteReader(); LoginModel.UserInfo user = null; //读取详细的数据 while (reader.Read()) { if (user == null) { user = new LoginModel.UserInfo(); } //读取查询到的数据 user.ID = reader.GetInt32(0); user.UserName = reader.GetString(1); user.Password = reader.GetString(2); } return user; } } } }
登陆:
结果显示: