三层——原先很头疼的例子

本文通过一个登录及积分功能的示例,详细介绍了三层架构的设计思路,包括数据库搭建、实体层、UI层、业务逻辑层和数据访问层的具体实现。

三层的从字面上理解很简单,但是后来的经历告诉我,字面上的不叫理解!但是,丑媳妇终究是要见婆婆的,再害怕的知识点也是迟早要学习滴!下面通过一个简单的(登陆+积分)的例子来了解一下让人头疼的三层!

、数据库搭建:新建一个Student 数据库,含有两张表:UserInfo 表和Scores表

UserInfo 表主要是存放登陆用户的登陆名和登陆密码的;Scores表记录用户登陆,每登陆一次,在表中添加用户的UserID和一个积分




解决方案资源管理器 UI层的窗体

、代码实现:

(1) 实体层:一句话;上穿下跳,将数据在各层之间进行传递

Public Class UserInfo
    Private user_id As String
    Private user_password As String
    ''' <summary>
    ''' 定义UserInfo属性 
    ''' </summary>
    ''' <value></value>
    ''' <returns></returns>
    ''' <remarks></remarks>
    ''' 

    Public Property UserID() As String  '定义UserInfo 的UserID 属性
        Get
            Return user_id              '从其他层中得到User_id并进行赋值
        End Get
        Set(ByVal value As String)
            user_id = value
        End Set
    End Property

    Public Property UserPassword() As String '定义UserInfo 的UserPassword属性
        Get
            Return user_password            '从其他层中得到User_password并进行赋值
        End Get
        Set(ByVal value As String)
            user_password = value
        End Set
    End Property

End Class
(2) UI层,从用户界面中获取用户的操作数据。

Public Class frmLogin

    Private Sub btnLogin_Click(sender As Object, e As EventArgs) Handles Button1.Click
        '引用了实体类和业务逻辑层,要实例化对应的对象
        Dim UiEntityUser As New Entity.UserInfo
        Dim UiBllLogin As New BLL.LoginManager

        '从UI层得到用户ID 和密码
        UiEntityUser.UserID = TextBox1.Text()
        UiEntityUser.UserPassword = TextBox2.Text()

        '转入到业务逻辑层,进行相关的业务逻辑的判断
        If UiBllLogin.UserLogin(UiEntityUser) = True Then
            MsgBox("登陆成功!")
        Else
            MsgBox("登陆失败!")
        End If

    End Sub

    Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles Button2.Click
        End
    End Sub
End Class

(3)业务逻辑层,进行各种业务逻辑的判断
Public Class LoginManager

Public Function UserLogin(ByVal User As Entity.UserInfo) As Boolean

 '引用了实体类和数据访问层,因此应该实例化实体类和数据访问层中对应的类

 Dim bllEntityUserInfo As New Entity.UserInfo
 Dim bllDalScore As New DAL.DBScore
 Dim bllDalUser As New DAL.DBUserInfo

 '将用户界面得到的用户输入的ID 赋值给实例化的实体类对象,从而转入到数据访问层进行查询
 bllEntityUserInfo.UserID = User.UserID
 bllEntityUserInfo = bllDalUser.DbCheck(bllEntityUserInfo)

 '过数据访问层从数据库查询的用户密码和用户输入的密码一致,进行数据库积分更新,并返回值
        If Trim(bllEntityUserInfo.UserPassword) = User.UserPassword Then
            bllDalScore.UpdateScore(User.UserID, 10)
            Return True
        Else
            Return False
        End If
    End Function

End Class

(4) 数据访问层;和数据库进行交互,是系统和数据库之间联系的纽带。

数据访问层有三个类:

a ) databaseConnecstr用来连接数据库

Public Class databaseConnecstr

    Public Shared Function Constr() As String
        Constr = "data source=192.168.24.82;database=Student; uid=sa;pwd=202414;"
    End Function

End Class

b)UserInfo 类,用来从数据库UserInfo表中检索相关信息。

Imports System.Data.SqlClient

Public Class DBUserInfo
    '
    Public Function DbCheck(ByVal User As Entity.UserInfo) As Entity.UserInfo
        '实例化访问数据库对象
        Dim conn As New SqlClient.SqlConnection      '连接数据库的字符串
        conn = New SqlConnection(DAL.databaseConnecstr.Constr())

        '定义查询语句
        Dim sql As String = "select * from UserInfo where UserID='" & User.UserID & "'"
        '执行查询语句
        Dim cmd As SqlCommand = New SqlCommand(sql, conn)
        Dim read As SqlDataReader

        Try
            conn.Open()
            read = cmd.ExecuteReader
            read.Read()

            '如果用户存在的话,将数据库表中检索的记录对应赋值给参数

            User.UserID = read.Item("UserID")
            User.UserPassword = read.Item("UserPwd")
            Return User  '返回User

        Catch ex As Exception
            '如果用户不存 将密码赋值为空,并将用户作为返回值进行返回
            User.UserPassword = ""
            Return User

        End Try

    End Function
End Class

c) Scores类,用户每登陆成功一次,给用户添加积分

Imports System.Data.SqlClient
Public Class DBScore

    Public Sub UpdateScore(userID As String, score As Integer)

        '定义连接数据的字符串和数据库执行命令
        Dim conn As SqlConnection = New SqlConnection(DAL.databaseConnecstr.Constr())
        Dim cmd As SqlCommand = conn.CreateCommand()

        '向数据库Scores 表中插入用户ID 和 积分
        cmd.CommandText = "insert into Scores(UserID,Score) values(@UserID,@Score)"
        cmd.Parameters.Add(New SqlParameter("@UserID", userID))
        cmd.Parameters.Add(New SqlParameter("@Score", score))

        '打开数据库连接 执行SQL语句之后,关闭
        conn.Open()
        cmd.ExecuteNonQuery()
        conn.Close()

    End Sub
End Class

三、其实,各层之间的相互调用,必须有引用关系才可以。当我们建立了UI , BLL,DAL以及实体类 等类库的时候,我们就应该在各个类库中添加相应的引用关系。只有这样,才会在各层调用的时候,不会出现“XXX 未定义”的错误!


PS:按照源码设计之后,还不一定能出现运行结果。如果运行的话,可能会出现:无法直接启动带有"类库输出类型"的项目。的错误。这是因为我们的启动项设置的不对,将UI层设为启动项,并在UI项目的My Project 中,将应用程序类型设置下图所示,这时就可以了!

总结:丑媳妇总是要见家人的,再难的知识点也是要学习滴~~~~~~

RealThinClient SDK Copyright 2004-2013 (c) RealThinClient.com All rights reserved. -------------------------------- ******************************** 1.) License Agreement 2.) Install RTC SDK components in Delphi 3.) Make the RTC SDK accessible from XCode (for iOS development) 4.) Update RTC SDK components in Delphi 5.) Help 6.) Demos 7.) Support ******************************** -------------------------------- --------------------- 1.) License Agreement --------------------- Please read the RTC SDK License Agreement before using RTC SDK components. You will find the RTC SDK License Agreement in the "License.txt" file. -------------------------------- 2.) INSTALL RTC SDK components in Delphi -------------------------------- After you have unpacked the files in a folder of your choice and started Delphi, open the "Package_Main" Project Group where you will find 3 packages: rtcSDK.dpk -> The main Package. Includes all Client and Server HTTP/S components. rtcSDK_DBA.dpk -> Optional, includes only "TRtcMemDataSet" and "TRtcDataSetMonitor" components. rtcSDK_RAW.dpk -> Optional, includes only raw TCP/IP and UDP communication components. Install the components in Delphi by using the "Install" button, or the "Install" menu option. In older Delphi versions, you will see the "Install" button in the Project Manager window. In newer Delphi versions, you will find the "Install" option if you right-click the package file in the Project Manager accessed in the "View" drop-down menu. When compiled and installed, you will see a message listing all components installed. After that, you should add the path to the RTC SDK's "Lib" folder to "Library paths" in Delphi. In older Delphi versions, the Library Path is located in the "Tools / Environment Options" menu. Select the "Library" tab and add the full path to the RTC SDK's "Lib" folder to "Library path". In newer Delphi versions, Library Paths are located in the "Tools / Options" menu. Select the "Environment Options / Delphi Options / Library" tree branch, where you will find the "Library Path" field. There, you should click the "..." button next to "Library path" and add the path to the RTC SDK's "Lib" folder. In Delphi XE2 and later, you will also see a "Selected Platform" drop-down menu. There, all the settings are separated by platforms, so you will need to repeat the process for every platform you want to use the "RTC SDK" with. ------------------------------- 3.) Make the RTC SDK accessible from XCode (for iOS development) - Delphi XE2 ------------------------------- For the FPC compiler to find RTC SDK files, you can either copy the complete "Lib" folder (with sub-folders) from the RTC SDK package into the "/Developer/Embarcadero/fmi" folder (quick and dirty solution), or ... You can add the path to the RTC SDK 揕ib?folder (located on your Windows PC, made accessible to Mac over LAN) to the FPC search path. Unfortunatelly, there is no 損arameter?for adding FPC search paths in XCode directly, so you will need to do this manually for every XCode Project. And not only once, but every time you recreate XCode Project files by using the 揹pr2xcode?tool, because all your changes will be overwritten by "dpr2xcode". To avoid having to make these changes too often, use "dpr2xcode" ONLY if you have made changes to the Project file itself (changed the Project icon, for example). There is no need to recreate XCode Project files if you have only changed forms or units inside the Project. To add the RTC SDK paths to FPC, you will need to modify the file "xcode/<ProjectName>.xcodeproj/project.pbxproj". The path to the RTC SDK 揕ib?folder needs to be added as two new ?Fu?parameters. Once for iOS-Simulator and once for iOS-Device compilation, both of are configured through the 搒hellScript?parameter. The best place to add the RTC SDK Lib path is after the FireMonkey path, so you should search for ?Fu/Developer/Embarcadero/fmi?in the above mentioned XCode Project file. You will find 2 such instances in the "ShellScript" line and you should add the path to the RTC SDK Lib folder directly after each "-Fu/Developer/Embarcadero/fmi" instance. For example, if you have made the complete RTC SDK folder on your Windows PC available to your Mac OSX through a network share named 揜TC_SDK?(read/write access rights to that folder will be required for FPC compilation to work), you should add ?Fu/Volumes/RTC_SDK/Lib?after both ?Fu/Developer/Embarcaedro/fmi?locations. One is for the iOS-Simulator, the other one for the iOS device. That will be enough to let FPC know where to look for RTC SDK files. Should you still get "File not found" errors when trying to compile a Project using RTC files, make sure the path you have used is correct and that Mac OSX has read and write access to that folder. PS. Before configuring access to the RTC SDK, you will need to have OSX 10.6 or 10.7, the latest XCode 4.x version and both packages provided by Embarcadero (included with RAD Studio XE2) installed on your Mac. To make sure your Mac OSX configuration is correct, create an empty "FireMonkey iOS HD" Project, use "dpr2xcode" to create XCode Project files and try to run that Project from XCode, either inside the iOS-Simulator or directly on your iOS device (iPhone or iPad). ------------------------------- 4.) UPDATE RTC SDK components in Delphi ------------------------------- Download the latest version of the RTC SDK from the RTC Support Forum: http://sf.realthinclient.com Information about recent RTC SDK updates is in the "Updates*.txt" file(s). To update RTC SDK components, it's adviseable to uninstall the old packages and delete the old BPL and DCP files (rtcSDK.bpl, rtcSDK.dcp, rtcSDK_DBA.bpl, rtcSDK_DBA.dcp, rtcSDK_RAW.bpl and rtcSDK_RAW.dcp) before installing new packages. To uninstall RTC SDK components, after you start Delphi, open the menu "Component / Install Packages ..." where you will see a list of all packages currently installed in your Delphi. Scroll down to find "RealThinClient SDK" and click on it (single click). When you select it, click the button "Remove" and Delphi will ask you if you want to remove this package. Clicking "Yes" will uninstall the RTC SDK. After that, *close* Delphi and follow step (2) to install the new RTC SDK package. NOTE: Uninstalling the RTC SDK package will also uninstall all packages which are using the RTC SDK (for example, rtcSDK_DBA, rtcSDK_RAW and "Nexus Portal" packages). So ... if you are using "Nexus Portal" or any other product using the RTC SDK, you will need to Build and Install all related packages again, after you reinstall the RTC SDK. ------------- 5.) Help ------------- The best place to start learning about RTC SDK is the QuickStart guide. After going through the online lessons, you should also go through the QuickStart examples included in the RTC SDK package. When you are done examining QuickStart examples, I suggest browsing through the FAQ. Even if you won't be reading all the articles, you should at least get the feeling about the information included there. RTC SDK Demos are another good source of information, including a lot of examples and best practices for using the RealThinClient SDK. And the most extensive source of information on the RealThinClient SDK are Help files. Some of the information is spread across the files, but if you know which class you need, you will most likely be able to find what you are looking for. When you start working on your project, the FAQ will come in handy when you have to do something specific (use Sessions, accept form post data, write and call remote functions, etc). The FAQ is continually being extended, as more questions come in. If you have a question for which you were unable to find the answer in the QuickStart guide, QuickStart examples or the FAQ ?and searching through the Help files didn't give you the answers you need, don't hesitate to post your question(s) on Developer Support groups. The latest Help file for Off-line viewing is in the "Help" folder: - "Help\RTCSDK_Help.chm" ------------------- 6.) Demos ------------------- You can find Demos using RTC SDK components in the "Demos" folder. Simple Quick Start Examples are available in the "QuickStart" folder. There are also 5 Project Groups which include all the Demos and Quick Start examples: * Demos_VCL - Demos using the VCL and the rtcSDK.dpk * Demos_VCL_DBA - Demos using the VCL with the rtcSDK.dpk and rtcSDK_DBA.dpk * Demos_FMX - Demos using FMX (Win,OSX,iOS) with the rtcSDK.dpk * Demos_FMX_DBA - Demos using FMX (Win,OSX,iOS) with the rtcSDK.dpk and rtcSDK_DBA.dpk * Examples_QuickStart_VCL - Short "QuickStart" examples using the VCL with the rtcSDK.dpk For short descriptions of available demos and quick start examples, please find the "Readme_Demos.txt" file in the "Demos" folder, and "Readme_QuickStart.txt" file in the QuickStart folder. ------------- 7.) Support ------------- More information on RTC SDK: > http://www.realthinclient.com/about.htm Download the latest version of RTC components and get Support through the RTC Forums: > http://sf.realthinclient.com
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值