之前用C#敲过一次三层登录,在用C#敲三层登录的时候已经将基本信息给介绍的比较全面了,所以这次用VB.NET敲完三层,也不做过多的介绍,只在这里将敲完三层所用的VB.NET的代码展示一下,有需要的可以借鉴一下,在第一次用VB.NET敲三层感到迷惑的时候可以参考这篇博客来实现一下代码。这也是我写这篇博客的主要目的,给大家带来帮助。OK,废话不说了,看代码:
Imports System.Data Imports System.Data.sqlClient Public Class UbUtil Public Shared Function Connstring() As sqlConnection Dim cnStr As String cnStr = "server=.;database=Login;User ID=sa;password=123" Dim coon As sqlConnection coon = New sqlConnection(cnStr) Return coon End Function End Class
然后再将DAL层的第二部分敲好。DAL第二部分的作用是用来接收BLL层所发出的信息然后再与数据库中相应位置的信息匹配,代码如下:
Imports System.Data Imports System.Data.sqlClient Public Class Selectsql Public Function SelectUserInfo(UserInfo As Model.UserInfo) As Model.UserInfo Dim cn As sqlConnection = sqlHelper.Connstring Dim sql As String sql = "SELECT * from Users where UserName = @UserName and Password = @Password" Dim cmd As sqlCommand = New sqlCommand(sql,cn) cmd.Parameters.Add(New sqlParameter("@UserName",UserInfo.UserName)) cmd.Parameters.Add(New sqlParameter("@Password",UserInfo.Password)) cn.Open() Dim reader As sqlDataReader reader = cmd.ExecuteReader() Dim User As New Model.UserInfo While (reader.Read()) User.UserName = reader.GetString(1) User.Password = reader.GetString(2) End While Return UserInfo End Function End Class
这样DAL层就已经大功告成,接下来就是敲Model模块,Model模块的作用就是连接整个流程,在敲完这个模块之后,再敲BLL层的话,就能顺利的让BLL层与DAL层成功连接,方便一步一步的调试,所以Model层的重要性是非常大的,代码如下:
Public Class Login.UserInfo Private Property e_userName As String Public Property UserName() As String Get Return e_userName End Get Set(value As String) e_userName = value End Set End Property Private Property e_Password As String Public Property Password() As String Get Return e_Password End Get Set(value As String) e_Password = value End Set End Property End Class
等Model模块敲完之后就可以继续敲BLL层了,BLL的作用是用来处理业务逻辑的,起到一个承上启下的作用。具体代码如下:
Public Class LoginManager Public Function checkUserinfo(ByVal UserInfo As Model.UserInfo) As Model.UserInfo Dim Login As New DAL.Selectsql Dim Manager As New Model.UserInfo Manager = Login.SelectUserInfo(UserInfo) If (Manager.UserName Is Nothing Or Manager.Password Is Nothing) Then Throw New Exception("用户名或密码错误,请核实~~~") End If MsgBox("登陆成功,正在登录系统",MsgBoxStyle.Information + MsgBoxStyle.OkOnly,"提示") Return Manager End Function End Class
最后就剩下UI层了,我所做的显示窗体是这样的:
其具体的代码如下:
Imports System.Windows.Forms Public Class Login Private Sub btnOK_Click(sender As Object,e As EventArgs) Handles btnOK.Click Try Dim UserInfo As New Model.UserInfo UserInfo.UserName = txtUserName.Text.Trim() UserInfo.Password = txtPassword.Text.Trim() If txtUserName.Text = "" Then MsgBox("用户名不能为空!","提示") Return End If If txtPassword.Text = "" Then MsgBox("密码不能为空!","提示") Return End If Dim Login As New BLL.Manager Dim returnUserInfo As New Model.UserInfo returnUserInfo = Login.checkUserinfo(UserInfo) Catch ex As Exception MessageBox.Show(ex.Message.ToString()) End Try End Sub End Class
大功告成,这就是VB.NET敲下的三层登录所有的代码,具体数据库的设置看代码应该能看出一些,数据库建立了一个表,表名为:Users
希望能帮大到家。