In this paper, the network database design based on three-layer architecture is introduced, combined with the theory of object-oriented, distributed database development. Full text around a typical and simple example, through VB programming language, from various angles of analysis, modeling, design, coding, a comprehensive and detailed explanation of the three-layer system and database, and all source code is provided.
Key words three-layer system database for object-oriented distributed development
Three-layer architecture
We often see that many candidates write the words "proficient database programming" on the resume, and often see some of the recruitment requirements of the software company on the recruitment website as "proficient database programming". So these applicants go to these software company interviews, so we have seen many "proficient" phenomena.
Some programmers are implemented when designing database applications, usually using methods of data control binding. Use the mouse to pull several controls, then set a few properties with the mouse, even the keyboard is not used, complete the development of a database application! Of course, this is indeed a fast database application development method, but it doesn't mean it quickly.
For large database application systems, or have many client applications, we need another "proficient", which is the "three-layer architecture" that almost every programmer has heard.
1.1. Traditional C / S mode
In the traditional database application system, the client is completely separated from the database, running most of the services on the client, such as data access rules, business rules, legitimacy checks, and more. Each client exists with a data engine, and each client establishes a separate database connection (DB Connection) with the database server.
Based on the advantage of the database application system: the development cycle is shorter, it can accommodate most of the small and medium-sized database application systems (when the number of clients is less than 50).
However, with the increasing development of the database application, the data capacity is increasing, the number of clients is increasing, and this architecture shows many flaws, mainly in the following aspects:
1, expandability: For the database server side, whenever a data connection is created, a large number of system resources will occupy a large number of system resources, and when the data connection reaches a certain amount (such as 20), the response speed and processing speed of the database server will be greatly reduced. .
2, maintainability: Based on traditional C / S database application, business rules are typically placed in client applications. If the business rules have changed (casual examples, if the ID number is possible to raise to 19), we must modify the client application and make each client's corresponding upgrade work.
3, reusability: When using traditional C / S design mode, database access, business rules, etc. are cured in the client application. If the customer adds to the application requirements of B / S, you need to re-perform database access, business rules, legitimacy checks in the web server (such as writing database access to ASP code), and the work and customers do The functions in the end application are completely repeated, thereby increasing the workload, making the program developers feel extremely uncomfortable.
Because many of the above defects make the three-layer (multi-layer) architecture becomes the first choice for current database application development, even customers sometimes present the technical needs.
1.2. Three-layer architecture
The so-called three-layer architecture is an "intermediate layer" that has been added between the client and the database, and is also called component layer. The three-layer system mentioned here is not a physical three-layer, not simply placing three machines is a three-layer architecture, not only B / S is the three-layer architecture, and the three layers are logical. Three layers, even if these three layers are placed on a machine.
The application of the three-layer system puts the business rules, data access, legitimate checks, etc. in the intermediate layer. Typically, the client is not interacting with the database, but is established with the intermediate layer via the COM / DCOM communication, and then interact with the database via the intermediate layer.
This kind of benefit is obvious:
1. Since the data access is performed by the intermediate layer, the client will no longer establish a data connection directly with the database. That is, the number of connections built on the database server will be greatly reduced. For example, a 500 client application system, 500 clients establish a DCOM connection with the intermediate layer server, and the system resources occupied by DCOM communications are extremely limited, and is dynamically established and released, so the number of clients will no longer be restricted. . At the same time, the data connection between the intermediate layer and the database server is connected to the connection number of connections, dynamic allocation and release data connections via "connecting pool", so the number of data connections is far less than the number of clients.
2, can be improved. Because the business rules, the legitimacy check is in the intermediate layer, so when the business rule changes, simply change a component (such as a DLL file) on the intermediate layer server, and the client application does not need to do anything. Sometimes, even if you don't even have to modify the intermediate layer components, you only need to modify a stored procedure in the database.
3, good reusability. Similarly, if you need to develop B / S applications, you don't have to re-perform the development of data access, business rules, etc., you can call existing intermediate layers directly on the web server side (if you can use IIS-based webclass development, or write ASP directly Code).
4. Transaction is more flexible and transaction can be performed in the database end, component layer, MTS (or COM ) manager.
If you still feel uninhabined now, you don't matter, please see the example below.
2. Simple personnel management system
The following is a very simple personnel management system to describe how to implement a three-layer architecture. The programming language is Visual Basic 6.0.
In order to fully introduce the programming method, different methods in VB code implement the same functions, such as database access, and stored procedures and ADO connections are used. The reader can choose the most suitable method yourself.
Since a large number of annotations are added in the code, the function function and principle are not explained too much.
In the team development, the notes in the code should account for about 1/3 of the entire code, and should write a note before the code is written. If another programmer thinks that you are not nonsense in your code, then these comments are definitely plus it after writing the code!
2.1. Demand
Simple department / personnel management system, requirements:
1. The attributes of the department have department names, and the attributes of the person have name, age, gender;
2, the department has the upper and lower level relationship;
3. The person must belong to a department;
4, personnel, department needs to increase, delete, modify functionality
5, can inquire according to the name of the person
6. If a department exists, or there is a lower department, the department cannot be deleted.
The above is the simple demand for the system.
2.2. Database
The database is designed with SQL Server 7. The database name is "TEST", there are two data sheets (where the reader has mastered the database design because this database is too simple).
Table TDEPT
Field Name Type Nid Int Deptname Char (50) SuperId Int
Temployee
Field Name Type Nid Int DeptId Int Empname Char (10) Empage Smallint Empgennder Bit
Where NID is associated with superid in TDEPT.
2.3. Intermediate layer
Open VB6, select "New ActiveX DLL" and reference ADO 2.5.
New Add a module, named MDLPublic, add 5 classes, named CDEPT, CEMP, CDEPTS, CEMPS, CPUBLIC, respectively. Among them, CEMPS and CDEPTS are collectible classes of CEMP and CDEPT, and cpublic is a class that defines enumerations, no practical significance. Set the startup module of the project to "Sub Main".
Add a stored procedure AddDEPT in the TEST library of SQL Server.
All code is as follows:
2.3.1. MDLPUBLIC.BAS
Option expedition
Public G_CN AS Connection 'For global data connection
The startup program of 'ActiveX DLL is performed for DLL initialization
Public Sub Main ()
IF connection Then = false
Err.raise vbobjectError 1, "Connect the database error!"
END IF
End Sub
'Connect to the database
Public Function ConnectTodatabase () as boolean
ON Error Goto Err_Conn
Set g_cn = new connection
'Set the server name, database name, login name (at this point, it is empty)
DIM ServerName As String, DBName As String, UserName As String
ServerName = "GXC-NOTEPAD"
DBNAME = "Test"
UserName = "sa"
'Connect to the database
WITH G_CN
.CURSORLOCATION = aduseclient
.Commandtimeout = 10
.Connectionstring = "provider = SQLOLEDB.1; PERSIST security info = true; user ID =" & username "; initial catalog =" & dbname & "; data source =" & servername
.Open
End with
ConnectTodatabase = TRUE
EXIT FUNCTION
Err_Conn:
ConnectTodatabase = FALSE
END FUNCTION
'Detailed single quotes in the string
Public Function RealString (Strorigional) AS STRING
RealString = Replace (Structrorgional, "'", "")
END FUNCTION
'Get the next value of the primary key in a data sheet, that is, the current primary key value plus 1
Public Function NextId (Byval Strid As String) AS LONG
'Two parameters are the name of the table and the name of the primary key
DIM RS as Recordset
SET RS = g_cn.execute ("SELECT MAX (" & strid & ") from" & start "if isnull (RS (0)) THEN
'If the value is null, there is no data record without any data. At this time, the ID should be 1
NextID = 1
Else
'Make the new ID to the maximum ID value 1
NextID = rs (0) .value 1
END IF
END FUNCTION
'View a data table, there is a record that is equal to a value (integer)
Public Function Existbyid (Byval Strid As String, Byval LNGID As Long) AS Boolean
'The first parameter is a table name, the second is the field name, the third is the specific field value.
DIM RS as Recordset
SET RS = g_cn.execute ("Select Count (*) from" & Strtable & "Where" & strid & "=" & lngid)
EXISTBYID = (RS (0) .value = 1)
END FUNCTION
'View a piece of data, whether there is a field equal to a certain value (character type)
Public Function ExistbyName (Byval StrfieldName As String, Byval Strname As String, Byval thisid as long) as boolean
'The first parameter is a table name, the second is the field name, the third is the specific field value.
DIM RS as Recordset
SET RS = g_cn.execute ("Select Count (*) from" & Strtable & "WHERE" & STRFIELDNAME & "& STRNAME &" 'and NID <> "& thisid)
EXISTBYNAME = (RS (0) .value = 1)
END FUNCTION
'The above two functions can actually merge, in this program, for explanation, so separate
2.3.2. Cpublic.cls
Option expedition
'This class doesn't actually, just for some custom enumerations
'Customize enumeration, used to express gender
Public Enum GxcGender
Male = 1
Female = 0
END ENUM
'' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' Following enumerations for "department" objects
'Used to indicate the enumeration of the department deletion
Public Enum Gxcdelete
Deleteok = 0
Deletefail = 1 'Unknown causes causing not deleted
DELETESUBEXISTS = 2 'Due to the existence of a sub-part, it cannot be deleted
Deleteempexists = 3 'The department has a person, cannot be deleted
END ENUM
'Used to indicate the enumeration of the department update results
Public enum gxcupdate
Updateok = 0
Updatefail = 1
DuplicateName_Update = 2 'Name is not repeatable
RecordNotexist = 3 'The current updated record has been deleted by other clients
END ENUM
'Used to indicate an enumeration in the new results of the department
Public enum gxcaddnew
AddNewok = 0
AddNewfail = 1
Duplicatename_addnew = 2 'Name is not repeatable
SuperNotexist = 3 'The ID of the above-specified superior department does not exist
END ENUM
'' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '
2.3.3. Cdept.cls
Option expedition
Private mvardeptname as string
Private mvarid as long
Private mvarsuperid as long
'' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '
'The following is the attribute of the department
'Superior department ID
Public Property Let Superid (Byval VData As Long)
mvarsuperid = VDATA
End Property
Public Property Get Superid () as longsuperid = mvarsuperid
End Property
'The ID of this department
Public Property Let ID (Byval VData As Long)
mvarid = vdata
End Property
Public property get id () as long
ID = MVARID
End Property
'Name of this department
Public property Let DePtName (Byval VData As String)
VDATA = trim (vdata) 'removes spaces on both sides
'The length of the control name is not greater than 50
IF LEN (VDATA)> 50 Then vData = Left (VDATA, 50)
mvardeptname = vdata
End Property
Public property get deptname () AS STRING
Deptname = mvardeptname
End Property
'End of the attribute
'' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' ''
'' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' ''
'
'Add a department and return the results of the operation
Public Function AddNew (optional strname as string = ", _
OPTIONAL LNGSUPERID AS Long = -1) AS GXCADDNEW
'Update attribute values based on incoming parameters
ON Error Goto Err_Addnew
'If the parameter is incorporated, the attribute is updated with incoming parameter.
If strname <> "" Then me.deptname = STRNAME
If LNGSUPERID <> -1 Then Me.superid = LNGSUPERID 'ID of the superior department
'Call the stored procedure through the Command object, by the stored procedure
'The operation of adding the department and returns the result of the operation by the stored procedure.
DIM CMD as adodb.command
Set cmd = new adoDb.command
WITH CMD
Set .activeConnection = g_cn
.Commandtype = adcmdstoredProc 'Sets the command type "stored procedure" .commandtext = "adddept"' stored procedure name
'Incorporate two parameters, the name of the department and the ID of the superior department
.Parameters.Append .createParameter ("@ name", adchar, adparaminput, 50, me.deptname)
.Parameters.Append .createParameter ("@ superid", Adinteger, Adparaminput,, Me.superid
'Incorporate two return type parameters, return to the new record ID and operation results, respectively
.Parameters.Append .createParameter ("@ ID", Adinteger, Adparamoutput)
.Parameters.Append .createParameter ("@ return", adINteger, adparamoutput)
.Execute
End with
DIM RTN As GxcaddNew
RTN = cmd.parameters ("@ return"). Value 'gets the results
'If the operation is successful, you will assign the ID value to the object.
IF RTN = addnewok kil = cmd.parameters ("@ id"). Value
AddNew = RTN 'Returns the results
SET cmd = Nothing
EXIT FUNCTION
ERR_ADDNEW:
'Come here, then explain it wrong.
IF not cmd is nothing the set cmd = Nothing
AddNew = addnewfail
END FUNCTION
'Modify the department information, return to the results
Public function update () AS GXCUPDATE
'Determine whether or not there is this record by ID, that is, whether the record is deleted by other clients.
'If there is no such record, return the corresponding operation result to the caller
IF NOTBYID ("TDEPT", "NID", Me.ID) THEN
Update = RecordNotexist
EXIT FUNCTION
END IF
'Judging whether there is a record of the same name by name, if there is the same name,
'The information returned to the caller "existence of the same name"
IF EXISTBYNAME ("TDEPT", "deptname", me.deptname, me.id) THEN
Update = duplicatename_update
EXIT FUNCTION
END IF
ON Error ResMe next
DIM STRSQL AS STRING
'Construct the SQL statement, pay attention to call the RealString function to remove single quotes in the string
strsql = "Update TdeptName = '" & RealString (me.deptname) & "" ","
Strsql = strsql & "superid =" & Iif (me.superid = 0, "null", me.superid)
strsql = strsql & "where nid =" & me.idg_cn.execute strsql 'Execute SQL statement
'According to whether it is wrong, return to the corresponding information corresponding to the caller.
IF err.number = 0 THEN
Update = Updateok
Else
Update = updatefail
END IF
END FUNCTION
'Delete a department
Public Function Delete (optional byval LNGID As Long = 0) AS GXCDELETE
'If you pass the ID when calling this function, update the ID of the object.
IF LNGID <> 0 Then me.id = LNGID
'If you have anyone under the department, you can't delete it.
IF EXISTBYID ("Temployee", "DeptID", Me.ID) THEN
Delete = deleteempexists
EXIT FUNCTION
END IF
'If there is a sub-sector under the department, you can't delete it.
IF EXISTBYID ("TDEPT", "superID", me.id) THEN
Delete = deleteSubexists
EXIT FUNCTION
END IF
ON Error ResMe next
'Execute the delete operation and return the results
g_cn.execute "delete from tdept where nid =" & me.id
Delete = IIF (Err.Number = 0, Deleteok, Deletefail)
END FUNCTION
'Get all employees from this department
Public Function Employees () AS CEMPS
DIM Objemps As New CEMPS
'Call the Find method of the CEMPS class, only the third parameter, ie "department ID"
SET Employees = Objemps.Find (,, me.id)
END FUNCTION
'Get all sub-sectors in this department
Public Function SubDepartments () AS CDEPTS
DIM Objdepts as new cdepts
'Call CDEPTS's Find method, look for the ID of the superior department
Set SubDepartments = ObjdePTS.Find (, Me.ID)
END FUNCTION
'Get the superior department of this department, return to the object
Public Function SuperDepartment () AS CDEPT
DIM Objdepts as new cdepts
'Call CDEPTS's Find method, use "superID" of this class as a lookup condition
'To find out its superior sector
Objdepts.find me.superid
If Objdepts.count> 0 THEN SET SUPERDEPARTMENT = ObjdePTS.Item (1)
END FUNCTION
'End of the method
'' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' 2.3.4. Cdepts.cls
Option expedition
Private Mcol as Collection
Add a "department" object to the collection
Public Sub Add (Objdept As CDEPT)
Mcol.Add Objdept, "a" & objdept.id
'In the addition, it is best to add its "key" attribute.
The '"key" attribute can not be a digital type, so it is just added in front.
'One letter, this adds a "a"
End Sub
Public property Get Item (VNTINDEXKEY As Variant) AS CDEPT
Set item = mcol (VNTINDEXKEY)
End Property
Public property get count () as long
Count = mcol.count
End Property
Public Sub Remove (VNTINDexKey As Variant)
Mcol.remove VntindexKey
End Sub
Public property Get Newenum () AS IUNKNOWN
'This property allows the collection to enumerate the collection with for ... EACH syntax.
Set newenum = mcol. [_ Newenum]
End Property
'Clear all the elements in the collection
Public Sub Clear ()
'note! You must be removed inverted during clearance, otherwise it's wrong!
DIM I as long
For i = mcol.count to 1 step -1
Mcol.remove i
Next I
End Sub
Private sub coplass_initialize ()
Set mcol = new color
End Sub
Private sub coplass_terminate ()
Set mcol = Nothing
End Sub
'Find the department according to the conditions to return in a set class.
Public Function Find (Optional LNGID As long = 0, OPTIONAL LNGSUPERID AS long = -1) as cdepts
'Press the input parameter query and return a collection class
DIM STRSQL AS STRING
'Construct SQL statement
strsql = "SELECT * from TDEPT WHERE"
If LNGID <> 0 Then strsql = strsql & "nid =" & lngid & "" "
IF lngsuperid <> -1 Then
If LNGSUPERID = 0 Then 'If you pass 0, it means there is no superior department.
Strsql = strsql & "superid is null and"
Else
Strsql = strsql & "superid =" & lngsuperid & "AND"
END IF
END IF
Strsql = strsql & "nid> 0"
'Empty the current collection
Me.clear
DIM RS as Recordset
SET RS = g_cn.execute (strsql)
Add query results in the collection
DIM I as long
DIM Objdept as cdept
For i = 1 to rs.recordcount
Set objdept = new cdept
With objdept
.Id = rs ("NID"). Value
.Deptname = trim (RS ("deptname"). Value)
.SUPERID = IIF (ISNULL ("Superid"). Value, 0, RS ("SuperID"). Value)
End with
Me.Add Objdept
Set objdept = Nothing
rs.movenext
Next I
SET RS = Nothing
SET FIND = ME
END FUNCTION
2.3.5. CEMP.CLS
Option expedition
Private mvarid as long
Private mvarempname as string
Private mvarempage as in
Private mvarempgenender as gxcgender
Private mvardeptid as long
Private mvardeptname as string
'' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '
'The following attributes
'Department name
Public property Let DePtName (Byval VData As String)
mvardeptname = vdata
End Property
Public property get deptname () AS STRING
Deptname = mvardeptname
End Property
'Department ID
Public property Let DeptId (Byval VData As Long)
mvardEptid = VDATA
End Property
Public property get deptid () as long
DeptID = mvardeptid
End Property
'gender
Public Property Let Empgen (Byval VData As GxcGender)
mvarempgender = VDATA
End Property
Public property Get EmpGender () AS GXCGENDER
Empgen = MvarempGender
End Property 'age
Public Property Let Empage (Byval VData As Integer)
IF VDATA <0 Then VDATA = 1 'is not less than 0
mvarempage = vdata
End Property
Public property Get Empage () AS Integer
Empage = mvarempage
End Property
'Name
Public property Let Empname (Byval VData As String)
VDATA = trim (vdata) 'removes spaces on both sides
'The length of the control name is not greater than 10
IF LEN (VDATA)> 10 Then vData = Left (VDATA, 10)
mvarempname = VDATA
End Property
Public property Get Empname () AS String
Empname = mvarempname
End Property
'Id
Public Property Let ID (Byval VData As Long)
mvarid = vdata
End Property
Public property get id () as long
ID = MVARID
End Property
'End of the attribute
'' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' ''
'' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' ''
'
'Add a person
Public Function AddNew (optional byval strname as string = ", _
Optional byval intage as integer = 0, _
Optional vargender as gxcgen = -1, _
OPTIONAL LNGDEPTID AS Long = 0) as boolean
ON Error ResMe next
'If the parameter is the default value, that is, the parameters in the direct tuning class, otherwise call the incoming parameters.
IF strname <> "" Then me.empname = strname
IF INTAGE <> 0 Then me.empage = intage
If vargender <> -1 Then me.empgen = vargender
If LNGDEPTID <> 0 Then me.deptid = LNGDEPTID
DIM STRSQL AS STRING
g_cn.begintrans
'Start a business, avoiding the ID value has been used by other clients
'Call nextID method here, get the next ID of the corresponding data sheet, that is, the maximum ID 1
Me.id = NextID ("Temployee", "NID")
'Construct the SQL statement, pay attention to the demarcation to remove single quotes in the string
STRSQL = "Insert Into Temployee (NID, DEPTID, Empname, Empage, Empgen) Values ("
strsql = strsql & me.id & "," & me.deptid & ","
strsql = strsql & "'" & realstring (me.empname) & "" ","
Strsql = strsql & me.empage & "," & me.empgennder & ")"
'Execute SQL statements and submit transactions
g_cn.execute strsql
g_cn.committrans
'If an error occurs, return false, indicating that it is not successful.
AddNew = (Err.Number = 0)
END FUNCTION
'Modify personnel information
Public function update () as boolean
ON Error ResMe next
DIM STRSQL AS STRING
'Construct SQL statement
strsql = "Update Temployee Set DeptId =" & Me.deptid & ""
Strsql = strsql & "empname = '" & realstring (me.empname) & "" ","
strsql = strsql & "Empage =" & me.empage & "
strsql = strsql & "EmpgenDer =" & Me.empgender & "
strsql = strsql & "where nid =" & me.id
g_cn.execute strsql
'If an error occurs, return false, indicating that it is not successful.
Update = (err.number = 0)
END FUNCTION
'Delete personnel information
Public Function Delete (Optional Byval LNGID As long = 0) as boolean
DIM STRSQL AS STRING
ON Error ResMe next
'If you have passed the ID to be deleted, press this ID to delete
IF LNGID <> 0 Then me.id = LNGID
strsql = "delete from timeee where nid =" & me.idg_cn.execute strsql
'If an error occurs, it returns false, indicating that the successful success is not deleted.
Delete = (Err.Number = 0)
END FUNCTION
'End of the method
'' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' ''
'Move someone to the designated department
Public Function AssignTodepArtment (Byval Deptid As Long) As Boolean
'Implementing very simple, change the department ID, then call the Update method.
Me.deptid = deptid
AssignTodepartment = me.update
END FUNCTION
'Get the department where the person is located, return it to the object
Public function department () AS CDEPT
DIM Objdepts as new cdepts
'Call CDEPTS's Find method to get department
Objdepts.find me.deptid
If Objdepts.count> 0 THEN SET Department = ObjdePts.Item (1)
END FUNCTION
2.3.6. CEMPS.CLS
Option expedition
Private Mcol as Collection 'Local Variable, Save Collection
'Add a "person" object to the collection
Public Sub Add (Object AS CEMP)
Mcol.Add Objemp, "a" & objemp.id
'When adding an object, it is best to add its "key" attribute.
The '"key" attribute can not be a digital type, so it is just added in front.
'One letter, this adds a "a"
End Sub
Public property Get Item (VNTINDEXKEY AS VARIANT) AS CEMP
Set item = mcol (VNTINDEXKEY)
End Property
Public property get count () as long
Count = mcol.count
End Property
Public Sub Remove (VNTINDexKey As Variant)
Mcol.remove VntindexKey
End Sub
Public property Get Newenum () AS IUNKNOWN
'This property allows the collection to enumerate the collection with for ... EACH syntax.
Set newenum = mcol. [_ Newenum]
End Property
'Clear all the elements in the collection
Public Sub Clear ()
'Clear or clear!
DIM I as long
For i = mcol.count to 1 step -1
Mcol.remove i
Next I
End Sub
Private sub coplass_initialize () set mcol = new color
End Sub
Private sub coplass_terminate ()
Set mcol = Nothing
End Sub
'Find people according to the condition, return to the way in the collection class
Public Function Find (optional byval LNGID As long = 0, _
OPTIONAL BYVAL STRNAME AS STRING = "", _
OPTIONAL BYVAL LNGDEPTID AS Long = 0) AS CEMPS
'Construction query SQL
DIM STRSQL AS STRING
Strsql = "select Temployee. *, TDEPT.DEPTNAME from Temployee Left Outer Join Tdept"
strsql = strsql & "on tdept.nid = Temployee.deptid where"
If LNGID <> 0 Then strsql = strsql & "temployee.nid =" & lngid & "a"
'If you are queried by name, use the "included" query method.
If strname <> "" THEN STRSQL = strsql & "temployee.empname like '%" & realstring (strname) & "'% and"
If lngdeptid <> 0 damql = strsql & "temployee.deptid =" & lngdeptid & "a"
strsql = strsql & "temployee.nid> 0"
'Add the query result to the collection class
DIM RS as Recordset
SET RS = g_cn.execute (strsql)
DIM I as long
DIM Objemp as CEMP
For i = 1 to rs.recordcount
Set Objemp = New CEMP
With objemp
.Id = rs ("NID"). Value
.Empname = trim (RS ("Empname"). Value)
.Empage = rs ("empage"). Value
.Empgen = ABS (RS ("Empgener"). Value)
.Deptid = RS ("deptid"). Value
.Deptname = trim (RS ("deptname"). Value)
End with
Me.Add Objemp
Set Objemp = Nothing
rs.movenext
Next I
SET RS = Nothing
SET FIND = ME
END FUNCTION
2.3.7. AddDEPT stored procedure
CREATE Procedure AddDept
@Name char (50),
@Superid Int,
@ID Output,
@Return Int Output
AS
Begin Transaction
- If the superior department ID is 0, it is set to NULL, indicating that there is no superior department.
IF @ superid = 0 Select @ superid = null
- The current ID is the maximum ID value 1
SELECT @ id = (Select Max (NID) from Tdept) 1
- If the ID value is empty, it means that there is no record, and the person is assigned 1
IF @id is null select @ id = 1
- If there is the same department name, return the enumeration type defined in the VB code.
IF exists (Select * from tdept where deptname = @ name) Begin
SELECT @ Return = 2
Rollback Transaction
Return
end
- If there is no specified superior department ID, return to the enumerated type specified in VB.
IF not exists (select * from tdept where nid = @ superid) and not (@superid is null) begin
SELECT @ Return = 3
Rollback Transaction
Return
end
INSERT INTO TDEPT (NID, Superid, DeptName) Values (@ id, @ superid, @ name)
IF @@ Error = 0 Begin
SELECT @ return = 0
Commit transaction
ELSE BEGIN
SELECT @ RETURN = 1
Rollback Transaction
end
2.3.8. Component design considerations
At this point, you can take a closer study, mainly two basic classes (person objects and department objects), two set classes (personnel collection and sector collection). Here you can understand the collection as "array of objects".
Then, take a closer analysis of these four structures, interfaces, interrelationships, then draw them out (please do this, it will help you better understand the object-oriented). Do you find a new interface function? of course! Because the code in this article is just an example, they need to be perfect for your continued, such as you can package the "payment" into the "person" class.
Save the above code as mycom.vbp and compile to generate mycom.dll files. The DLL file is an intermediate layer component.
In this component, we have added a large number of business rules, such as "age cannot be less than 0", can not delete a sub-sector or superior department, there is no deletion in the department, and the department name cannot be greater than 50 characters.
When performing any programming, the convenience of the user must be considered. For example, when designing an application, we are always considering how to make direct users more conveniently, if the operational logic is more acceptable.
Similarly, the design of the COM component should also be considering the user, how to make users more conveniently. Users of COM components are not end users, but the programmer! Is a programmer for making an interactive interface! Therefore, in designing the COM interface and the structure, it should be taken into account the interface programmer's thinking and convenience of use, such as the function, should be naming with a strong alphanumeric.
The most perfect state is this: Use the programmer of your COM component to think about: There should be such a function, and the name should be getCustomername, so he is really found in your component, and the function name Even the input parameters are exactly the same as he imagined, then you are really successful! After the COM component is written, it should be tested, and each function and attribute should be tested. You can write a simple test program for testing (sometimes in order to save time, you can test directly in the interface, but may increase the communication time of the programmer, sometimes it will be lost).
2.4. Client
Since the COM component (or the intermediate layer) has written completed and passed the test, the interface can be written below.
It is very interesting that the interface programmer can do not understand the database programming based on the design model of the three-layer architecture. He does not have to know the format of the database, and do not even have to know what type of database.
Please see the following example:
First, create a new project and then reference mycom.dll.
2.4.1. A few examples first
2.4.1.1. Add a department
Dim objdept as new cdept 'Defines a department object
Dim Result As GxcadDNew, Strresult As String
With objdept
.Deptname = "headquarters"
. Superid = 0 '0 indicates that there is no superior department
Result = .addnew 'gets the result of the operation
If result = addnewfail dam
Strresult = "Add failed!"
Elseif Result = duplicatename_addnew then
Strresult = "There are sectors of the same name, please modify the name and re-add!"
Elseif Result = SuperNotexist Then
Strresult = "The specified superior department does not exist or have been deleted!"
Else
Strresult = "Add success!"
END IF
End with
Msgbox Strresult, Vbinformation
With the above code, "adding a department" has been completed, and the results of the operation can be clearly known. There is no place in the code that this is programming the database.
The top three lines in the WITH block in the above code can also be replaced with one of the following lines of code (because all the parameters in your addNew function are optional):
Result = .addNew ("headquarters", 0)
2.4.1.2. Delete a department
DIM Objdept As New CDEPT 'Defines a department object
Dim Result As Gxcdelete, Strresult As String
Result = Objdept.delete (1) 'Delete the department of ID 1
If Result = deleteempexists the
Strresult = "There is a person in the department, can't be deleted!"
Elseif Result = Deletefail Then
Strresult = "Delete failed!"
Elseif Result = deleteSubexists Then
Strresult = "There is a sub-sector in the department and cannot be deleted!" Else
Strresult = "successfully delete"
END IF
Msgbox Strresult, Vbinformation
2.4.1.3. Query all subsidiaries and departmental people
The following code looks out the department of the ID 12 and then gets all the personnel under the department with all sub-sector.
Dim objdepts as new cdepts, objemps as new cemps' Define department collection and personnel collection
IF Objdepts.Find (12) .count> 0 THEN
Set objemps = objdepts (1) .employees' Get all personnel in the department
Set objdepts = objdepts (1) .subDepartments' received all sub-sectors in the department
END IF
2.4.1.4. More interesting operations
The following code finds the first person to include "Zhang San", then find out all the colleagues in the same department.
DIM Objemps As New CEMPS
IF Objemps.Find (, "Zhang 3") .count> 0 THEN
'Get all the people of the same department
Set Objemps = Objemps (1) .Department.employees
END IF
The following code views whether Zhang San is Li Si's direct boss.
ON Error ResMe next
DIM Objemps As New CEMPS
IF Objemps.Find (, "Zhang 3") .Item (1) .Department is Objemps.Find (, "Li Si") .Item (1) .Department.superDepartment Then
Msgbox "Zhang San is Li Si's head boss!"
END IF
The above code may be rarely used in actual programming, or can never be used, but this also reflects the flexibility of component development from another aspect.
See this, if you still don't understand, please buy a book of VB primary entry, carefully study research.
2.4.2. Detailed interface example
Open VB, create a new project. Quote Mycom.dll just generated, add Microsoft usual control (Common Control 6.0).
Add a window frmmain, join a TreeViw, and the department used to display the hierarchical display, named TVWSHOW.
Add a listview, used to display the list of people, named lvwemp.
Join six buttons, used for department / personnel, change, delete (to better explain the problem, deliberately add six buttons, do not have this in actual development), named cmddddept, cmdeditDept, cmddeDept, cmdadDemp , cmdeditemp, cmddeleteemp.
Add an image list, add three icons that have a characteristic icon, which is "O", "D", "E", for root nodes, department, and personnel. And set the TVWSHOW image list to the control.
2.4.2.1. Display department, personnel to tree map
Add the following code to achieve the loading of the department and personnel.
'Add all departments to the tree diagram
Private subserseTotreeView (byref TVw as treeview)
DIM Objdepts as new cdepts
DIM I as long
'Join the department without superior sector
Objdepts.Find, 0Dim ND As Node
Set nd = tvw.nodes.add (, "o0", "all departments", "o") 'joins the original root node. "O0", the first one is the letter O, the second is the number 0
Nd.expanded = TRUE
For i = 1 to objdepts.count
'Join the department node without the superiors, the graphical list ID is "D"
Set nd = tvw.nodes.add ("o0", TVwchild, "a" & objdepts (i) .id, objdepts (i) .deptname, "D")
Nd.expanded = TRUE
'Loading its subordinate department nodes
Loadsubnodes TVW, ND, Objdepts (i) .id
Next I
End Sub
'Call recursive, display the department structure of the tree
Private sub purposesubnodes (byref TVw as treeview, nd as node, nodeid as ring)
DIM ND1 AS NODE
DIM Objdepts as new cdepts
DIM I as long
Objdepts.Find, NodeId 'found all sub-semen of the department
For i = 1 to objdepts.count
Set nd1 = tvw.nodes.add (nd, tvwchild, "a" & objdepts (i) .id, objdepts (i) .deptname, "D")
Nd1.expanded = true
'Recurrence loading subordinate department .....
Loadsubnodes TVW, ND1, Objdepts (i) .id
Next I
End Sub
'Add people to the tree diagram, have departmental nodes in the tree diagram
Private subunyeettereeView (byref TVw as treeview)
ON Error Resume Next 'This code is added to prevent errors, and the actual programming needs to be judged, in order to illustrate the problem.
DIM Objemps As New CEMPS
Objemps.Find 'found all the people
DIM I as long
For i = 1 to Objemps.count
Addemptotvw Objemps (i), TVW
Next I
End Sub
'The EmployeetteEeView one function can complete "joining personnel to tree map", but
'Taking into account the following functions, you need to use the following function, so extract the following code.
'Coming out, make a separate function. (For details, please refer to the code behind)
'Add a person to the tree diagram, display it under the appropriate department
Private sub addemptvw (ByVal Objemp as Cemp, Byref TVW As TreeView)
ON Error ResMe next
TVW.NODES.ADD "a" & objemp.deptid, TVwchild, "b" & objemp.id, objemp.empname, "e"
End Sub
'Add a department into the tree diagram
Private sub adddddtotvw (byval objdept as cdept, byref tvw as treeview)
ON Error ResMe next
If Objdept.superid = 0 THEN '"O0", the first is the letter O, the second is the number 0
TVW.NODES.ADD "O0", TVWChild, "a" & objdept.id, objdept.deptname, "D"
Else
TVW.NODES.ADD "a" & objdept.superid, tvwchild, "a" & objdept.id, objdept.deptname, "D"
END IF
End Sub
Add the following code in the Form_Load event:
Private sub flow_load ()
DepartmentTotreeView TVWSHOW 'Displays the department in the tree diagram
EmployeettereeView TVWSHOW 'also adds people to the same tree diagram
End Sub
At this point, you can manually add some records to the database, and then run the program. You will find that these code has realized the display of the department and personnel.
In the code above, you still have not seen any of the characteristics of any database programming.
2.4.2.2. Personset list box
The following code implements the function of displaying the person to the list box, refers to the code in the code.
'In accordance with the "Person" class, set the display style of ListView
Public Sub IITEMPLOYELISTVIEW (Byref Lvw As ListView)
WITH LVW
.View = lvwreport
.Labeledit = lvwmanual
.Gridlines = true
.Columnheaders.clear
'Join four lists
.Columnheaders.add,, "Name", 1000
.Columnheaders.add,, "department", 2000
.Columnheaders.add, "age", 800
.Columnheaders.add,, "gender", 700
End with
End Sub
'Display people in ListView
Public Sub EmployeestolistView (Byval Objemps As Cemps, Byref Lvw As ListView)
'Collection class and list box for incoming parameters
DIM I as long
'If the list is not initialized, then initialize (you can use other methods to determine if it is initialized, here is a stupid approach)
If lvw.columnheaders.count = 0 THENINITEMPLOEELISTVIEW LVW
Lvw.listItems.clear 'Clear the current list content
For i = 1 to Objemps.count
'Add each "person" to this list, call a separate function, not all this
In 'function, why? See the Addemptolvw function
Addemptolvw Objemps.Item (i), LVW, FALSE
Next I
End Sub
'Add a single person to the list or update in the list
'Delicate the function separately, and do not implement the code in this function completely in the EmployeestolistView function.
'Why?
'Because when you design the function, you should also take into account the future programming process, it is likely to use it.
'Add a separate "person" object to the list box (for example, a new person).
Public Sub Addemptolvw (Byval Object AS CEMP, BYVAL ISOVERWRITVIEW, BYVAL ISOVERWRITE AS BOOLEAN) 'The third parameter If it is true, it is that it is updated to have a list item that is currently existing, otherwise it is a new list item.
DIM ITM As ListItem
If isoverwrite dam
Set itm = lvw.selectedItem
IF itm is nothing the exit sub
Else
SET ITM = lvw.listitems.add (, "a" & objemp.id)
END IF
With objemp
Itm.text = .empname
Itm.subitems (1) = .deptname
Itm.subitems (2) = .empage
ITM.SUBITEMS (3) = Iif (.empgenDer = Female, "Female", "Men")
End with
Set itm = Nothing
End Sub
Add the following code rows in Form_Load (make it a first line code):
INITEMPLOEELISTVIEW LVWEMP 'Initialization list
To this end, we have completed basic display operations, down a question is: When you select a tree frame diagram node (such as a department node), how can I instantiate this object, that is, acquire the object from the interface? Please continue.
2.4.2.3. Retrieve the object from the control
In the above code, when we see, when the object is added to the control, if the control is a tree pattern, we set the key value of the node to the letter "A object ID" (for the root node is the letter O number 0, for the department The node is the letter A. The person node is the letter B, which is to prevent Key repetition), if the control is a list box, set the key value of the list item to the same value.
In this way, the ID value can be retrieved by the Key property. So add one of the following functions and retrieve the ID value.
'Get the actual ID of the object represented by a node or list item, such as "A1", get 1, "b2", then get 2
Private function getId (strkey as string) As long
GetID = Val (Right (strkey, len (strkey) - 1))
END FUNCTION
Add the following functions, the function function and the principle are referred to the code annotation (don't worry, it is very simple).
'Get a person object from a list or tree pattern
Public Function GetEmpfromControl (ByVal CTL As Object, Byref Objemp As CEMP) AS Boolean
'If there is no item selected in the list, you directly exit it.
If CTL.SelectedItem is nothing then
GetEmpfromControl = false
EXIT FUNCTION
END IF
DIM Objemps As New CEMPS
DIM ID as long
'Remove the letters "a" before the Node or list item of the control, that is, the ID value of the person
ID = getId (CTL.SelectedItem.Key)
ON Error ResMe next 'In order to prevent unconfidden, an error judgment statement set objectp = objemps.find (ID) .Item (1)
GetEmpfromControl = (Err.Number = 0)
END FUNCTION
'Get a department object from the tree pattern
Public Function getDeptfromtreeView (byval TVw as treeview, byref objdept as cdept) as boolean
If TVw.selecteditedItem is nothing kiln
DIM Objdepts as new cdepts
'The key lookup object in the selected node
If Objdepts.Find (getId (tvw.selecteditem.key)). Count = 0 THEN EXIT FUNCTION
On Error ResMe next 'In order to prevent unconfidden, an error judgment statement is added
Set objdept = Objdepts.Item (1)
GetDeptfromtreeView = (Err.Number = 0)
END FUNCTION
The use of the above function is followed by the following code.
2.4.2.4. Department increase, deletion, change
Because the department, the personnel exist in a tree pattern, so the user should have different operational functions after clicking different nodes, refer to the following code.
Private sub TVWSHOW_NODECLICK (byval node as mscomctllib.node)
DIM FLAG AS STRING
Flag = left (node.key, 1) 'gets the currently selected node type
'Set all buttons to not available
DIM CTL AS Control
For Each CTL in Controls
If Typeof CTL IS commandButton Then CTL.Enabled = false
NEXT
SELECT CASE FLAG
'Choose a root node, increasing the department at this time
Case "O"
cmdadddept.enabled = TRUE
Case "a"
'Choose a department node, you can increase, delete, change department and increase
cmdadddept.enabled = TRUE
cmdeditDept.enabled = TRUE
cmddeletedept.enabled = true
cmdaddemp.enabled = true
'Show all people under the department to the list box
'This is purely for demonstration, and the actual application may have more requirements.
DIM Objemps As New CEMPS
Objemps.Find, GetId (Node.Key)
EmployeestolistView Objemps, Lvwemp
Case "B"
'Choose a person node, you can delete, modify the person
cmdedItemp.enabled = TRUE
cmddeleteemp.enabled = true
End SELECT
End Sub
The following demonstrates how to achieve an increase in the department, modify and delete functions. Note that because there is only one "department name" attribute in the department, we can use the input box to edit the department.
Private sub cmdadddept_click ()
'' Increase the department
DIM STRNAME AS STRING
Strname = trim (InputBox ("Please enter the department name:"))
If strname = "" "The EXIT SUBDIM OBJDEPT AS New CDEPT
Dim Result As GxcadDNew
Result = objdept.addnew (Strname, GetId (TVWShow.SelectedItem.Key))
If Result = addnewok
'Add the department to the tree.
AddDepttotvw Objdept, TVWSHOW
Elseif Result = duplicatename_addnew then
Msgbox "There is a rename department, rename it!"
Else
Msgbox "failed!"
END IF
End Sub
Private subddeletedEpt_click ()
'Delete the department
IF msgbox ("Really deleted?", Vbquestion vbyesno vbdefaultbutton2) = VBNO THEN EXIT SUB
DIM Objdept as cdept
IF getDeptfromtreeview (TVWShow, objdept) = false kiln sub
Dim Result as gxcdelete
Result = Objdept.delete
If Result = deleteempexists the
Msgbox "Exemplary personnel, can not be deleted"
Elseif Result = deleteSubexists Then
Msgbox "There is a sub-department, can not be deleted"
Elseif Result = Deletefail Then
"Delete failed!"
Else
'Coming here, explain the deletion success, remove nodes from the tree diagram
TVWShow.Nodes.Remove TVWShow.selectedItem.index
Refreshbutton
END IF
End Sub
Private subdeditePt_click ()
'Editorial department
DIM Objdept as cdept
IF getDeptfromtreeview (TVWShow, objdept) = false kiln sub
DIM STRNAME AS STRING
'Default display of the department name of the original department
Strname = trim ("Please enter a new department name:", Objdept.deptname))
If strname = "" "The EXIT SUB
Dim Result as gxcupdate
Objdept.deptname = strname
Result = Objdept.Update
If Result = Updateok Then
'Add the department to the tree.
TVWShow.selectedItem.text = objdept.deptname
Elseif Result = duplicatename_update then
Msgbox "There is a rename department, rename it!"
Else
Msgbox "failed!"
END IF
End Sub
Add one of the following functions.
Private sub refreshbutton ()
'The six buttons on the refresh interface.
'Why do you want this? such as:
'You have chosen a "person" node now, then you can click the "Modify" button. 'But if you delete this person, there is no node in the tree model, and
'The option may be a department node, at this time your "modified person" button should be unavailable.
'status. So this function should be called whenever the person or department is deleted.
If TVWShow.selecteditem is nothing kiln eXIT SUB
TVWSHOW_NODECLICK TVWSHOW.SELECTEDITEM
End Sub
Try it, you can make an increase in departmental, delete, modify!
2.4.2.5. Personnel increase, delete, modify
Why introduce people from the department? We can make a new and modified work in a department through a input box, but because the personnel have a lot of properties, it may be necessary to implement through a separate window, for example, some text boxes, drop-down list boxes, two buttons, two buttons Used to confirm and cancel.
One feature of object-oriented programming is the concept of "object" throughout the program code. For example, you need to add or edit a "person", and decide to pop up a separate window for editing and display (such as a modal window, name femp), then the window is inevitable between the window and the main window.
You may think about writing the following code.
Private sub addemoyeedemo ()
'Do "modify one person" in this function
'Suppose an Objemp object is already instant there
WITH FEMP'FEMP is an editor's modal window
.Show 'shows the editing window
'Take the value from the editing window
Objemp.empname = .txtname.text
Objemp.empage = val (.txtage.text)
If .cbogender.listindex = 0 THEN
Objemp.empgen = feedale
Else
Objemp.empGender = MALE
END IF
'The following may also judge legitimacy, such as age can't enter letters, etc.
'' 'IF input is not legal?
End with
'Through the above code, we have achieved it from the "increasing / modified person" window.
'Section of data, thus constructing a "person" object, which can be used in the following
'Increase or delete or modify the operation, such as:
IF Objemp.Update = True Then
'.....
Else
'.....
END IF
End Sub
The above code is of course possible to run correctly, but if you do more in the FEMP window, you will make the code better, the following is the code of the FEMP window:
Option expedition
Private ok as boolean 'determines that the user presses OK or the Cancel button
Private Objemp as CEMP
Private isaddnew as boolean 'This parameter indicates that the window is open to add or modify
The ID of the private departmentID as long 'The department is located, if it is modified, this variable is useless
Private sub cmdok_click ()
'Check if the name is entered, or if you enter the age correctly
IF TRIM (TXTNAME) = "" or not isnumeric (txtage) THEN
Msgbox "Please enter the legal name and age"
EXIT SUB
END IF
Ok = true 'If it is a new state, a "person" object is newly established
IF isaddnew the set objectp = new CEMP
'Assigning the "person" object
Objemp.empage = val (txtage)
Objemp.empname = trim (txtname)
Objemp.empGender = CBoGENDER.LISTINDEX
'If it is a new state, set the department's department ID
If isaddnew the objemp.deptid = departmentID
Me.hide
End Sub
Private subcmdcancel_click ()
'Press the cancel button
OK = false
Me.hide
End Sub
Private sub setstatus ()
'According to "new" or modified, determine display content
IF isaddnew then
TXTNAME.TEXT = "" "
TXtage.Text = "20"
CBoGender.listIndex = 0
Else
TXTNAME.TEXT = Objemp.empname
TXtage.Text = Objemp.empage
CBoGender.listIndex = Objemp.empGender
END IF
End Sub
Public Function Retrieveemp (Byref Oemp As CEMP, OPTIONAL DEPTID AS long = -1) as boolean
Set Objemp = OEMP
'Get the ID of the department, if it is an edit state, this ID is useless
DepartmentID = DeptID
IsadDNew = (DeptID <> -1) 'is determined to be addressed or edited according to whether it is incorporated into the "department ID"
SetStatus' Settings content based on new or editing status
Me.Show VBModal
IF ok = false kiln exit function
Set Oemp = Objemp
Retriveemp = TRUE
Unload me
END FUNCTION
The above is all the code of the FEMP window, which has two text boxes, which are used for the name and age, and a drop-down list box is used for gender input (the list index just corresponds to the enumeration in the class), Two buttons (OK and Cancel).
It can be seen that the window provides a unique portal function RETRIEMP, which has two parameters. The first parameter is an object variable, and the second parameter is an optional parameter, which means the department ID to which the person belongs.
In this way, we can implement the information of the modified person by the following code:
'Suppose an Objemp object is already instant there
Ifmp.retriveemp (Objemp) = false kil
IF Objemp.Update = True Then
Else
END IF
We can see that only one function can be completed from the "Modify" window. Different, we wrote a lot of code in the FEMP window. This is the concept of the package, that is, we package the FEMP window into a class for new / modify the person information. This class has only one entry, RETRIEVEEMP. If you need to add or modify personnel information in other parts of the program, just simply call this function, do not need to be repeatedly written. Even, you can do a function alone, as follows:
Public Function GetMyemp (byref objemp as ceMp) as boolean
'This is just to give an example, don't do this in the program code.
GetMyemp = feedp.retriveemp (Objem)
End Sub
Let's continue.
Add the following code to the FRMMAIN for the increase, deletion, and change:
Private subdaddemp_click ()
'New personnel
DIM Objemp as CEMP
Ifmp.retriveemp (Objemp, GetId (TVWShow.SelectedItem.Key) = false kiln x
IF Objemp.addnew = True Then
Addemptotvw Objemp, TVWSHOW
Else
MSGBOX "error"
END IF
End Sub
Private subddeleteemp_click ()
'Delete personnel
IF msgbox ("To delete people?", Vbinformation vbyesno vbdefaultbutton2) = VBNO THEN EXIT SUB
DIM Objemp as CEMP
IF getEmpfromControl (TVWSHOW, Objem) = false kiln sub
IF Objemp.delete = True Then
TVWShow.Nodes.Remove TVWShow.selectedItem.index
Refreshbutton
Else
MSGBOX "error"
END IF
End Sub
Private subdeditemp_click ()
'Editorial person
DIM Objemp as CEMP
IF getEmpfromControl (TVWSHOW, Objem) = false kiln sub
Ifmp.retriveemp (Objemp) = false kil
IF Objemp.Update = True Then
Addemptolvw Objemp, Lvwemp, True
TVWShow.selectedItem.text = Objemp.empname
Else
MSGBOX "error"
END IF
End Sub
OK! You can run the entire program!
2.4.3. Expand
The above example tells how to implement the display and acquisition of the object and the interface. You may think of these methods in the class, and the operation may be more easier. Of course you can do this!
But sometimes there is no need to do this, just do a separate module on the interface side for interface display operations, if the intermediate layer and user interface is not in a machine, this result may increase network transmission . Moreover, some clients may need to display the content into different controls (such as grid, drop-down list, etc.).
For VB languages, interface design can actually be more flexible. But no matter which way it takes, always pay attention to it: what you do should make your customers use comfort! For example, the above FEMP window provides only a function interface, which encapsulates a lot of code (of course you can make the window more robust). Remember, when you do this window, your users are other programmers - other programmers calling the window, so much more convenient to think about them, how to call them more convenient. When you really do this, you will be a truly "team spirit" programmer!
Remember, for this code, try to do it, fully test, then throw it up to the brain!
2.5. Expansion is B / S
Once you have done two classes with "personnel", we can use their interface anywhere without having to write repetitive code multiple times - this is why the reason for writing a lot of code in the component.
Now, if you want to be a B / S version of the program, work is much simpler. Since there is an intermediate layer component, and the components include all business logic and interfaces, in the ASP code (assuming ASP development), you can directly use the various objects and interfaces provided in the components, do not have to establish a database connection, record The returns of the set, and the legality is more repeated. The figure below shows the principle of this reusability.
3. Summary
It can be seen from the above examples that a large number of code is written during the development of the intermediate layer, and the amount of code in the interface is also scary. In fact, in the above example, the amount and workload of the multilayer architecture are probably 2-3 times the conventional C / S workload.
So why should I use a three-layer architecture?
You can think that the above example is a "pure" three-layer architecture, which is the most ideal architecture. And in order to introduce more detailed, I wrote a lot of comments inside; more, some of the code is fully simplified and optimized by programming skills, which is in detail, which is purely to better explain the problem. Optimized code amount can be reduced by half.
When you start using this method for the first time, it may extend the development cycle, and your boss who doesn't understand the computer (assuming that he really doesn't understand) may also be conspicuous, why use new technology Instead, increase development costs, extend the development cycle?
The answer is simple. Because you or your development team has not accumulated. When you use this method to do two projects, you will find that many components can be reused, maybe just a small modification.
One suggestion: In order to reduce the code input, the "Class Build Tool" of VB can be used to generate the class.
If you carefully study, you will find that all physical classes (ie, actually existing business objects) correspond to one of the entities in the database, and their properties also correspond to the corresponding fields in the data table. And all of the ADDNEW, DELETE, UPDATE methods. If your project group often wants a similar project, you can do a "code generator", read the database structure from the database, directly generate all class modules - Of course you need a small amount of modification.
If you are an excellent project manager, you can organize someone who has mastered different skills into a project group, some members may be good at interface production, some good at database programming, some good at assembly design, even some people will not be VB, they use Delphi or C . A excellent project manager can make the project smoothly through reasonable division of labor, but maybe until the project ends, some project team members have no chance to understand the structure of the database, and some programmers don't even know what the program is long, but project It is indeed based on quieter! This article completes the entire code design with VB, if you don't use VB, or disdain to use VB, then the above method is still applicable, we pay attention to the architecture and overall ideas.
In fact, many programmers have often seen for programming language levels, they are very careful in programming language. But as a software personnel, or a software development team, even a software company, what is advanced? The author believes that effective is advanced! Similarly, the most advanced is often not necessarily effective.
I believe that for any programmer, since the software industry is engaged in the software industry, your goal cannot be a programmer, you might list system analysts, project managers, and high-level development management as your struggle. Since this, don't picky the programming language, otherwise, you can only be a programmer! Although you might be a great programmer.
Of course, the concept of the three-layer architecture is far from here, excellent distributed application development process, used to analyze / design / program / test, UML modeling, software development process control, parallel development, and iteration Many advanced technology and philosophy of development and many in the amount of development.
Object-oriented technology not only makes software development processes easier to control, software stability, quality is improved, and is quite beneficial for methods of analyzing problems in other areas. Long-term engagement, you will find the fun of the river, which is endless!
Word original download
(Full text)