本人由于刚接触不久,所以有许多借鉴的地方,希望大家多多指教。
下面的例子仅仅为了说明分层的概念,所以都是奔着尽可能简单的原则,没有实际意义
首先在sql SERVER中建一个数据库,命名为“SanCengTester”;再建一个表,命名为“User_Info”;然后添加一个字段“Name”。
下面就以在表“User_Info”中插入一个用户为例来讲述三层的实现
一、打开VS,新建空解决方案,具体如下:
1、文件→新建→项目
2、展开其它项目类型→Visual Studio解决方案→空白解决方案
3、起一个名字,并确定(如下图)
二、添加项目
右击资源管理器中刚建的解决方案(Tester)->添加->新建项目
按下图方式,依次添加Model、DAL、BLL三个类库
添加一个Windows窗体应用程序(命名为WinFormUI)
创建WinForm后按下图设计窗体
三、三层代码实现
实体(Model)层(为三层之间进行数据传递)
'实体(Model)层,实际就是实体类。为三层之际传递数据 Public Class ClassModel '定义UserName属性(字段) Private UserName As String Public Property name As String Get Return UserName End Get Set(ByVal value As String) UserName = value End Set End Property End Class
数据访问层(DAL)(对数据库的查询(select)和非查询(insert、delete、update)操作进行封装)
'先在DAL中加入对Model的参考,再加入如下代码
Imports Model Imports System.Data.sqlClient Public Class ClassDAL Dim sConn As String Dim dbConn As sqlConnection '获取数据库连接对象 Public Function getConn() As sqlConnection sConn = "server=.;database=SanCengTester;integrated security=sspi" dbConn = New sqlConnection(sConn) Return dbConn End Function '执行插入的sql命令 Public Function getCom(ByVal model As ClassModel) As Boolean Dim sqlstring As String = "insert into User_Info(Name)values('" + model.name + "')" Dim sqlconn As sqlConnection = Me.getConn() sqlconn.Open() Dim sqlcom As sqlCommand = New sqlCommand(sqlstring,sqlconn) Try sqlcom.ExecuteNonQuery() Return True Catch ex As Exception MsgBox(ex.Message) Return False Finally sqlcom.Dispose() sqlconn.Close() sqlconn.Dispose() End Try End Function End Class
业务逻辑层(BLL)(执行具体业务逻辑,连接UI层和DAL层)
'先在BLL中加入对Model和DAL层的引用再加入如下代码 Imports Model Imports DAL Public Class ClassBLL Dim dal As New ClassDAL Public Function getCom(ByVal model As ClassModel) As Boolean Try model = New ClassModel Return dal.getCom(model) Return True Catch ex As Exception MsgBox(ex.Message) Return False End Try End Function End Class
用户界面层(UI)(接收和显示数据)
'先在WinFormUI中加入对Model、Bll、DAL层的引用再加入如下代码 Imports Model Imports DAL Imports BLL Public Class FormUI Private Sub btnOk_Click(ByVal sender As System.Object,ByVal e As System.EventArgs) Handles btnOk.Click Dim txtmodel As New ClassModel txtmodel.name = txtUserName.Text.Trim() Dim bll As New ClassBLL If (bll.getCom(txtmodel)) Then MsgBox("恭喜,插入用户成功!") Else MsgBox("抱歉,插入用户失败!") End If End Sub Private Sub Button1_Click(ByVal sender As System.Object,ByVal e As System.EventArgs) Handles Button1.Click End End Sub End Class至此小例完成。。。