有了上一篇博客的理论基础,不过,纸上学来终觉浅,下面我们实践一下!三层视频里面老师讲解的非常详细,代码是C#版的,下面我们就来看一下VB.NET版的三层登陆吧!其实与C#是一样的。
首先先看一下UI层。
代码如下:
'表现层 Public Class LoginUI Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Try '获得UI层数据,传给BLL层 Dim euser2 As New Entity.UserInfo '实例化新的UserInfo,用来传递B层的实体 Dim euser3 As New Entity.UserInfo '定义一个类型为UserInfo的参数,用来赋值 euser2.UserName = txtUserName.Text.Trim '将用户名传给实体层Username euser2.Password = txtPassword.Text.Trim '将密码传给实体层的Password '调用B层,登录判断 Dim mgr As New LoginBLL.LoginBLL euser3 = mgr.UserLogin(euser2) Catch ex As Exception '异常处理 MessageBox.Show(ex.Message.ToString()) End Try End Sub End Class
'业务逻辑层 Public Class LoginBLL Public Function UserLogin(ByVal User As Entity.UserInfo) As Entity.UserInfo '实例化DAL层中新的UserDAO对象 Dim uDao As New LoginDAL.UserDAO '定义一个类型为实体层的UserInfo的参数,用来赋值 Dim eUser1 As Entity.UserInfo eUser1 = uDao.SelectUser(User) '判断是否存在用户名 If IsNothing(eUser1.UserName) Then Throw New Exception("登录失败,请检查用户名和密码!") Else MsgBox("登录成功!", , "登陆成功") Return eUser1 End If End Function End Class
再来看一下DAL层。这一层只涉及对数据库的操作。
Imports System.Data Imports System.Data.SqlClient Imports Entity '数据访问层 Public Class UserDAO '创建数据库连接为本机 Public conn As New SqlConnection("server=localhost;database=login;user id=sa;password=199312"; Public Function SelectUser(ByRef User As UserInfo) As Entity.UserInfo '传实体UserInfo,可方便对实体中的参数进行调用 Dim reader As SqlDataReader '定义类型为sqlDatareader的变量reader Dim eUser As New Entity.UserInfo '实例化新的UserInfo '查询关键字改成参数形式 Dim sql As String = "Select UserName,Password From Users where UserName=@UserName And Password=@Password" Dim cmd As New SqlCommand(sql, conn) '创建sqlCommand对象 cmd.CommandText = sql cmd.CommandType = CommandType.Text cmd.Parameters.Add(New SqlParameter("@UserName", User.UserName)) cmd.Parameters.Add(New SqlParameter("@Password", User.Password)) conn.Open() '打开数据连接 reader = cmd.ExecuteReader() '执行查询语句,并生成一个DataReader '读取查询到的数据,并返回相应的属性 While reader.Read() '获取数据中相应字段的数据 eUser.UserName = reader.GetString(0) '数组必须从0读取,否则会超出界限 eUser.Password = reader.GetString(1) End While Return eUser '返回查询到的实体 conn.Close() '关闭连接 End Function End Class
还有实体层,一般我都是在一开始先敲实体层的
'实体层,存放User的属性 Public Class UserInfo 'Username属性 Private _username As String Public Property UserName As String Get Return _username End Get Set(value As String) _username = value End Set End Property 'Password属性 Private _password As String Public Property Password As String Get Return _password End Get Set(value As String) _password = value End Set End Property End Class
三层登陆只是一个小小的例子,更深层次的应用,还在以后!