通过查资料,敲例子,对三层也有了一定的理解,下面是我通过对三层的学习之后,敲的一段机房收费系统中登录界面的例子。希望大家多多提出宝贵意见!
界面:
实体类-Model(和数据库表对应)
Public Class User Private name As String Private password As String Private Userid As String Private level As String Private account As String '以下为可读写属性 Public Property user_name() As String Get Return name End Get Set(ByVal value As String) name = value End Set End Property Public Property user_id() As String Get Return Userid End Get Set(ByVal value As String) Userid = value End Set End Property Public Property user_pwd() As String Get Return password End Get Set(ByVal value As String) password = value End Set End Property Public Property user_level() As String Get Return level End Get Set(ByVal value As String) level = value End Set End Property Public Property user_account() As String Get Return account End Get Set(ByVal value As String) account = value End Set End Property End Class
UI层-表现层 (界面的操作)
Public Class Form1 Private Sub butCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles butCancel.Click End End Sub Private Sub butOK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles butOK.Click '定义一个实体类对象,将文本框中的内容赋给实体类对象 Dim thisUser As Model.User = New Model.User thisUser.user_id = txtUserID.Text.ToString() thisUser.user_pwd = txtUserPWD.Text.ToString() '定义一个业务逻辑层对象,根据业务逻辑层返回的结果,通知用户信息 Dim uB As BLL.UserBLL = New BLL.UserBLL If uB.query_user(thisUser) Then MsgBox(True) Else MsgBox(False) End If End Sub End Class
BLL层-业务逻辑层 (将数据层的数据返回,传递数据)
Public Class UserBLL '定义一个D层的对象 Dim db As DAL.UserDB = New DAL.UserDB '此函数的作用是返回D层的执行结果 Public Function query_user(ByVal model As Model.User) As Boolean Return db.Query_User(model) End Function End Class
DAL层-数据访问层 (数据库连接,查询语句)
Imports System.Data.SqlClient Public Class UserDB '数据库连接语句 Dim str As String = "Data Source=localhost;Initial Catalog=Charge;Persist Security Info=True;User ID=sa;Password=123456" Dim conn As SqlClient.SqlConnection Public Sub New() '构造函数 建立连接,打开数据库 conn = New SqlClient.SqlConnection conn.ConnectionString = str conn.Open() End Sub '查询数据库中的用户是否存在 Public Function Query_User(ByVal tstUser As Model.User) As Boolean '数据库查询语句 Dim sqlstr As String sqlstr = "Select * From user_info Where user_id='" & tstUser.user_id & "' And user_PWD = '" & tstUser.user_pwd & "'" '查询 Dim sqlcmd As SqlClient.SqlCommand = New SqlClient.SqlCommand(sqlstr, conn) Dim myReader As SqlDataReader '定义一个reader用来读数据 myReader = sqlcmd.ExecuteReader() '运行你的查询,结果到myReader If myReader.Read() Then '如果查到了数据 Return True Else Return False End If End Function End Class
总结:
学习了三层架构,将一个系统分成DAL,BLL,UI层,实现了客户端和数据库之间的解耦,当我需要改动某一项功能时,只需改动本层的结构,这样大大的提高了系统的可维护性和可扩展性。
当然与我们之前用vb做的机房收费系统的登陆功能相比,当时不管是操作数据库的还是响应用户的需求等,所有的实现均在放在一起实现,分不清层次,用到什么就打开什么,对于系统的可理解性和维护性都不符合编码要求。
三层的使用,使得系统有一定的层次,方便理解,当需求改动时不需要大范围的修改,而且系统也易于扩展。