【开篇】
小编对于C#刚入门,Vb.net也是初学者,但是有一颗敢做的心,每天逼迫自己进步这是小编现在的生活。对于编程,以小编看来,就是高仿,模仿实例,在调试代码中成长,代码不是看会而是敲会的,纠结好久的问题也就迎刃而解。问题是我看着其他人的代码敲,自己什么都没有学会啊,都是别人的。接触新知识,大家可能都会有这样的一个认识,很吃力,很费劲。类似于我们小时候学骑自行车的时候,总是摔倒一样的,起先敲代码,大多的时候都是在调试错误中,不断总结经验,才可以敲出正确的代码。让我们一起骑车去看风景吧!!!
【VB.net版】
Entity层:
<span style="font-family:KaiTi_GB2312;font-size:18px;"><strong>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LoginModel { public class UserInfo { public string UserName { get; set; } public string Password { get; set; } } } </strong></span>
<span style="font-family:KaiTi_GB2312;font-size:18px;"><strong>Imports Model Imports BLL Public Class Form1 Private Sub btnLogin_Click(sender As Object, e As EventArgs) Handles btnLogin.Click Try Dim euser2 As New Model.User '实例化一个user,用来传递B层的实体 Dim euser3 As Model.User '定义一个类型为users的参数,用来赋值 euser2.UserName = txtUsername.Text.Trim '将用户名传给实体层的UserName euser2.password = txtPassword.Text.Trim '将密码传给实体层的PassWord '调用B层,登录判断 Dim mgr As New BLL.LoginManager euser3 = mgr.UserLogin(euser2) Catch ex As Exception MessageBox.Show(ex.Message.ToString()) End Try End Sub End Class </strong></span>
<span style="font-family:KaiTi_GB2312;font-size:18px;"><strong>Public Class LoginManager Public Function UserLogin(ByRef User As Model.User) As Model.User Dim uDAO As New LoginDAL.UserDAO '实例化D层中心的UserDAO对象 Dim euser1 As Model.User '定义一个类型为实体层User的参数,用于赋值 euser1 = uDAO.SelectUser(User) '判断是否查询到记录, 若有, 登录成功, 并返回实体user1 If IsNothing(euser1.UserName) Then Throw New Exception("登录失败,请检查用户名和密码!") Else MsgBox("登录成功!") Return euser1 End If End Function End Class </strong></span>
<span style="font-family:KaiTi_GB2312;font-size:18px;"><strong>Imports System.Data Imports System.Data.SqlClient Imports Model 'D层,只涉及到对数据的操作,需要引用实体层Model Public Class UserDAO '创建数据库连接 Public conn As New SqlConnection("Server=(local);Database=Login;user id=sa;password=6") Public Function SelectUser(ByRef User As User) As Model.User Dim reader As SqlDataReader Dim eUser As New Model.User Dim sql As String = "Select * From Users Where UserName=@Username And Password=@password" Dim cmd As New SqlCommand(sql, conn) cmd.CommandText = sql cmd.CommandType = CommandType.Text cmd.Parameters.Add(New SqlParameter("@Username", User.UserName)) cmd.Parameters.Add(New SqlParameter("@password", User.password)) conn.Open() reader = cmd.ExecuteReader() While reader.Read() eUser.UserName = reader.GetString(0) eUser.password = reader.GetString(1) End While Return eUser conn.Close() End Function End Class </strong></span>