【三层架构】——.Net代码分析

时间:2021-08-31 03:51:06

用.Net来写三层的登录窗体和上篇【C#登陆代码】写的基本思路是一样的,只是代码的规范不同,稍有差异不同。代码如下:


Entity层:作为实体层在U B D层之间进行传递


Public Class UserInfo
'定义私有属性
Private UserID As String
Private Password As String

'定义属性的过程,通过这个允许其他类访问,get set可以读写
Public Property ID As String
Get
Return UserID
End Get
Set(value As String)
UserID = value
End Set
End Property

Public Property PWD As String
Get
Return Password
End Get
Set(value As String)
Password = value
End Set
End Property
End Class

U层:实现用户交互界面,数据采集和显示


Public Class Form1
Private Sub btnLogin_Click(sender As Object, e As EventArgs) Handles btnLogin.Click
'实例化Model层对象
Dim Uuser As New Login.Model.UserInfo
'实例化B层对象
Dim BCheck As New Login.BLL.LoginManager

'将文本框中内容传给实体类LoginUser
Uuser.ID = txtUserName.Text()
Uuser.PWD = txtPassword.Text()

'判断登录,调用B层的方法
If BCheck.SelectUserAndBLL(Uuser) Then
MsgBox("登录成功")
Else
MsgBox("登录失败")
End If

End Sub
End Class

B层:传递和进行逻辑判断的作用


Public Class LoginManager
'实例化D层和Model层对象
Dim uDao As New Login.DAL.UserDAO
Dim Buser As New Login.Model.UserInfo

'定义一个函数,参数是user,类型是布尔值
Function SelectUserAndBLL(ByVal user As Login.Model.UserInfo) As Boolean
Buser.ID = user.ID
Buser = uDao.SelectBLLAndDAL(Buser) '引用DAL层

If Buser.PWD.Trim() = user.PWD Then
Return True
Else
Return False
End If

End Function
End Class

D层:连接数据库


Imports System.Data.SqlClient

Public Class UserDAO
'登录数据库 两种登录方式
Dim sqlConnectStr As String = "server=HOME-LOVE\MSSQLSERVER1;database=Login;User ID=sa;Password=1"
'Dim sqlConnectStr1 As String = "server=HOME-LOVE\MSSQLSERVER1;database=Login;integrated Security=true"

'查询数据库,用户是否存在
Function SelectBLLAndDAL(ByVal user As Login.Model.UserInfo) As Login.Model.UserInfo
'连接数据库
Dim sql As String = "select * from Users where Username='" & user.ID & "'"

'Connection连接数据库
Dim sqlConnect As SqlConnection = New SqlConnection(sqlConnectStr)
sqlConnect.ConnectionString = sqlConnectStr

'Command对象对数据库执行命令
Dim cmd As SqlCommand = New SqlCommand(sql, sqlConnect)
cmd.CommandText = sql '获得SQL语句的具体内容
cmd.Connection = sqlConnect


Dim read As SqlDataReader '从数据源读取数据
Dim UserDataTable As New DataTable '定义一个DataTable对象
Dim Duser As New Login.Model.UserInfo '定义Model层对象

Try
sqlConnect.Open() '打开连接
read = cmd.ExecuteReader '返回一个数据集对象
UserDataTable.Load(read)
Duser.ID = UserDataTable.Rows(0)("Username") '将数据库信息传给Model
Duser.PWD = UserDataTable.Rows(0)("Password")
Return Duser '返回实体层对象
Catch ex As Exception
Duser.PWD = ""
Return Duser
Finally
If Not IsNothing(sqlConnect) Then
sqlConnect.Close()
End If
End Try

End Function
End Class