敲一个例子比登天还难,一头雾水,无从下手啊。我的理解能力。。。。那就从最简单地三层登陆例子开始吧。
传递的是实体,userinfo,而不是具体的参数。
首先,UI层需要添加引用Entity和BLL层,BLL层需要添加引用DAL和Entity,而DAL需要添加引用Entity。Entity中定义了很多的参数,这些参数在三层之间传递。
按照引用的顺序,我们先需要敲entity层,他里面的参数是数据库中的字段,按着敲就可以啦。接着需要敲DAL层,他里面定义了数据库的连接。之后就是BLL层啦,接着就是UI层。
Public Class Userinfo Private _UserID As String Private _level As String Private _PWD As String Private _Statues As String Private _Username As String Public Property UserID As String Get Return _UserID End Get Set(value As String) _UserID = value End Set End Property Public Property PWD As String Get Return _PWD End Get Set(value As String) _PWD = value End Set End Property Public Property Statues As String Get Return _Statues End Get Set(value As String) _Statues = value End Set End Property Public Property Level As String Get Return _level End Get Set(value As String) _level = value End Set End Property Public Property Username As String Get Return _Username End Get Set(value As String) _Username = value End Set End Property End Class里面和数据库中的字段都是一一对应的。可读可写。
Imports System.Data Imports System.Data.SqlClient Imports Entity Public Class UserLogin Public conn As New SqlConnection("server=.;database=computer;user ID=sa;PWD=123456") Public Function SelectUser(ByVal User As Entity.Userinfo) As Entity.Userinfo '传递实体userinfo,而不是参数ID,username等,这样方便对实体等参数进行调用 Dim reader As SqlDataReader '定义类型为sqldatareader的变量reader Dim eUser As New Entity.Userinfo '实例化新的userinfo Dim sql As String = "select UserID,PWD from User_info where UserID=@username and PWD=@password " Dim cmd As New SqlCommand(sql, conn) '创建sqlcommand对象 cmd.CommandText = sql '获取sql语句的具体内容 cmd.CommandType = CommandType.Text cmd.Parameters.Add(New SqlParameter("@username", User.UserID)) cmd.Parameters.Add(New SqlParameter("@password", User.PWD)) conn.Open() '打开数据库 reader = cmd.ExecuteReader '执行查询语句,并生成DataReader While reader.Read() '获取数据库中相应字段的数据 eUser.UserID = reader.GetString(0) eUser.PWD = reader.GetString(1) End While Return eUser '返回查询到的实体 conn.Close() '关闭连接 End Function End Class
Public Class LoginManager Public Function UserLogin(ByVal User As Entity.Userinfo) As Entity.Userinfo Dim uDao As New DAL.UserLogin Dim eUser1 As New Entity.Userinfo eUser1 = uDao.SelectUser(User) '将数据传给D层 If IsNothing(eUser1.UserID) Then Throw New Exception("登陆失败,请验证登录名和密码") Else MsgBox("登陆成功") End If End Function End Class
Public Class Form1 Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Try Dim euser2 As New Entity.Userinfo Dim euser3 As New Entity.Userinfo euser2.UserID = TextBox1.Text.Trim '将U层数据传递给实体 euser2.PWD = TextBox2.Text.Trim Dim mgr As New BLL.LoginManager '将数据传递给B层 euser3 = mgr.UserLogin(euser2) Catch ex As Exception MessageBox.Show(ex.Message.ToString()) End Try End Sub End Class
对于三层的理解,还需要多多的实践啊。。。。。。