VB.NET 簡單三層登入例項
阿新 • • 發佈:2018-12-26
首先在vs 中建立相應的類庫以及窗體,各層操作如下:
首先明確一點,我寫的三層例項是以傳實體層中的實體為例子的。UI層引用BLL層和Entity層,BLL層引用DAL層和Entity層,DAL層引用Entity層。
實體層(Entity)建立資料庫中的實體類名稱為EntityUserinfo。
UI層建立FrmLogin窗體,如圖:
BLL層建立名稱為LoginBLL的類庫,DAL層建立名稱為LoginDAL的類庫。
各層程式碼如下:
Entity:(主要就是用於傳 實體 用,貫穿與 U層 B層 和 D層,三個層)
Public Class EntityUserInfo
'定義兩個私有屬性
Private id As String
Private password As String
'定義屬性過程,通過屬性過程,允許他的類訪問該屬性
Public Property UserID() As String
Get
Return id
End Get
Set(value As String)
id = 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
UI層:(使用者介面,接收和現實資料)
Public Class FrmLogin
Private Sub btnOK_Click(sender As Object, e As EventArgs) Handles btnOK.Click
'例項化 傳 實體的 物件 userinfo
Dim userinfo As New Entity.EntityUserInfo
'例項化 BLL層 的物件 loginbll
Dim LoginBll As New BLL.LoginBLL
'將文字框中的字串賦值給 實體物件 userinfo ,使實體物件能夠帶上引數
userinfo.UserID = txtUserName.Text.ToString
userinfo.PWD = txtPassword.Text.ToString
'例項化一個實體層 的 model 物件
Dim model As New Entity.EntityUserInfo
'呼叫BLL層的方法(返回值為 實體物件,所有上面定義一個 實體物件model)
'通過呼叫Bll層的方法,返回實體物件,比較model的屬性是否與文字框一致
model = LoginBll.UserLogin(userinfo)
If model.UserID = txtUserName.Text And model.PWD = txtPassword.Text Then
Me.Hide()
Applycation.Show()
Else
MessageBox.Show("登陸失敗")
End If
End Sub
BLL層:(業務邏輯層,呼叫DAL層的方法,被UI層呼叫 即連線UI層和DAL 層)
Imports Entity.EntityUserInfo
Imports DAL.LoginDAL
Public Class LoginBLL
'定義一個函式方法 userlogin 傳遞的引數為 實體層型別的變數 model 返回值為 一個實體
Public Function UserLogin(ByVal model As Entity.EntityUserInfo) As Entity.EntityUserInfo
'定義DAL層 的 物件LoginDAL
Dim LoginDAL As New DAL.LoginDAL
'定義實體層 物件 userinfo
Dim userinfo As New Entity.EntityUserInfo
'呼叫DAL層的方法,返回 實體
userinfo = LoginDAL.selectuser(model)
Return userinfo
End Function
End Class
DAL 層(資料訪問層,實現資料庫的連線)
Imports System.Data.SqlClient
Imports System.Data
Imports Entity.EntityUserInfo
Public Class LoginDAL
'資料庫連線,將資料庫連線定義為建構函式,當例項化 LoginDAL 的時候,自動完成資料庫連線
Dim str As String = "server=.;database=Charge_System;integrated security=sspi" '這裡字串用的是windows 驗證方式,所有不需要使用者名稱和密碼的操作。
Dim conn As New SqlConnection(str)
'在資料庫中查詢資料,執行命令語句
Public Function selectuser(ByVal model As Entity.EntityUserInfo) As Entity.EntityUserInfo
'連線資料庫
conn.Open()
Dim sql As String = "select * from T_Users where UserID= '" & model.UserID & " ' and PWD= '" & model.PWD & "'"
Dim cmd As New SqlCommand(sql, conn)
'定義一個 SqlDataReader 型別的變數 reader
Dim reader As SqlDataReader
reader = cmd.ExecuteReader() '由於cmd 物件的屬性 EcecuteReader 返回之是一個DataReader,所以只能定義一個Datareader型別的變數來接收資料。
'例項化一個實體層的物件 userinfo
Dim userinfo As New Entity.EntityUserInfo
'reader.read 的返回值為true 執行給 userinfo 的屬性賦值操作
While (reader.Read())
userinfo.UserID = reader.GetString(0)
userinfo.PWD = reader.GetString(1)
End While
'返回 實體物件 userinfo
Return userinfo
End Function
End Class
三層例項到此結束,有不到之處歡迎指正。