C\#중 3 층 구조의 실현 을 분석 하 다.

11866 단어 OacleC++cC#Access
본 고 는 C#1 에서 3 층 구 조 를 어떻게 실현 하고 MS Access 데이터 베 이 스 를 이용 하여 데 이 터 를 저장 하 는 지 토론 한다.또한 3 층 구조 에서 작은 재 활용 가능 한 구성 요 소 를 실현 하여 고객 데 이 터 를 저장 하고 추가,업데이트,고객 데 이 터 를 찾 는 기능 을 제공 합 니 다.
이 글 은 C#1 에서 어떻게 3 층 구 조 를 실현 하고 MS Access 데이터 베 이 스 를 이용 하여 데 이 터 를 저장 하 는 지 에 대해 논의 하고 있다.여기 서 저 는 3 층 구조 에서 작은 재 활용 가능 한 구성 요 소 를 실현 하여 고객 데 이 터 를 저장 합 니 다.추가,업데이트,고객 데이터 찾기 기능 을 제공 합 니 다.
배경
우선,나 는 3 층 구조의 이론 지식 을 소개 한다.간단 한 설명:3 층 구조 가 무엇 입 니까?3 층 구조의 장점 은 무엇 입 니까?
무엇이 3 층 구조 입 니까?
3 층 구 조 는'클 라 이언 트-서버'구조 로 이 구조 에서 사용자 인터페이스,상업 논리,데이터 저장 과 데이터 방문 은 독립 된 모듈 로 설계 되 었 다.주로 3 개 차원,1 층(표현 층,GUI 층),2 층(상업 대상,상업 논리 층),3 층(데이터 액세스 층)이 있다.이 층 들 은 단독으로 개발 하여 단독으로 테스트 할 수 있다.
왜 프로그램 코드 를 3 층 으로 나 누 었 습 니까?사용자 인터페이스 층,상업 논리 층,데이터 액세스 층 을 분리 하 는 것 은 많은 장점 이 있다.
빠 른 개발 에서 상업 논리 구성 요 소 를 다시 사용 합 니 다.우 리 는 시스템 에서 추가,업데이트,삭제,고객 데 이 터 를 찾 는 구성 요 소 를 실 현 했 습 니 다.이 구성 요 소 는 이미 개발 되 고 테스트 를 통 과 했 습 니 다.우 리 는 고객 데 이 터 를 저장 할 다른 프로젝트 에서 이 구성 요 소 를 사용 할 수 있 습 니 다.
시스템 이 쉽게 이전 되 고 상업 논리 층 과 데이터 액세스 층 은 분리 되 며 데이터 액세스 층 을 수정 하 는 것 은 상업 논리 층 에 영향 을 주지 않 습 니 다.시스템 이 SQL Server 로 데 이 터 를 저장 하 는 것 에서 Oracle 로 데 이 터 를 저장 하 는 것 으로 이전 하면 비 즈 니스 논리 계층 구성 요소 와 GUI 구성 요 소 를 수정 할 필요 가 없습니다.
시스템 은 쉽게 수정 된다.만약 상업 층 에 작은 수정 이 있다 면 우 리 는 사용자 의 기계 에 전체 시스템 을 다시 설치 할 필요 가 없다.우 리 는 상업 논리 구성 요소 만 업데이트 하면 된다.
응용 프로그램 개발 자 는 독립 적 인 개발 단독 층 을 병행 할 수 있다.
코드
이 구성 요 소 는 3 층 으로 되 어 있 으 며,첫 번 째 층 또는 GUI 층 이 라 고 불 리 는 form 으로 이 루어 져 있 으 며,FrmGUI 라 고 합 니 다.2 층 또는 비 즈 니스 논리 층,BOCustomer 라 고 부 르 며 Bussniess Object Customer 의 줄 임 말이다.마지막 으로 3 층 또는 데이터 층 이 라 고 부 르 며 DACustomer 라 고 부 르 며 Data Access Customer 의 줄 임 말이다.편 의 를 위해 서 나 는 세 층 을 한 항목 에 컴 파일 했다.
사용자 인터페이스 계층
다음은 사용자 인터페이스 로 된 코드 입 니 다.저 는 상업 논리 층 을 호출 하 는 일부 코드 만 선택 하 였 습 니 다.
//This function get the details from the user via GUI

//tier and calls the Add method of business logic layer.

private void cmdAdd_Click(object sender, System.EventArgs e)

{

try

{

cus = new BOCustomer();

cus.cusID=txtID.Text.ToString();

cus.LName = txtLName.Text.ToString();

cus.FName = txtFName.Text.ToString();

cus.Tel= txtTel.Text.ToString();

cus.Address = txtAddress.Text.ToString();

cus.Add();

}

catch(Exception err)

{

MessageBox.Show(err.Message.ToString());

}

}
 
//This function gets the ID from the user and finds the

//customer details and return the details in the form of

//a dataset via busniss object layer. Then it loops through

//the content of the dataset and fills the controls.
 
private void cmdFind_Click(object sender, System.EventArgs e)

{

try

{

String cusID = txtID.Text.ToString();
 
BOCustomer thisCus = new BOCustomer();
 
DataSet ds = thisCus.Find(cusID);
 
DataRow row;

row = ds.Tables[0].Rows[0];
 
//via looping

foreach(DataRow rows in ds.Tables[0].Rows )

{

txtFName.Text = rows["CUS_F_NAME"].ToString();

txtLName.Text = rows["CUS_L_NAME"].ToString();

txtAddress.Text = rows["CUS_ADDRESS"].ToString();

txtTel.Text = rows["CUS_TEL"].ToString();

}

}

catch (Exception err)

{

MessageBox.Show(err.Message.ToString());

}
 
}
 
//this function used to update the customer details.

private void cmdUpdate_Click(object sender, System.EventArgs e)

{

try

{

cus = new BOCustomer();

cus.cusID=txtID.Text.ToString();

cus.LName = txtLName.Text.ToString();

cus.FName = txtFName.Text.ToString();

cus.Tel= txtTel.Text.ToString();

cus.Address = txtAddress.Text.ToString();
 
cus.Update();

}

catch(Exception err)

{

MessageBox.Show(err.Message.ToString());

}

}


상업 논리 층
다음은 상업 논리 층 의 모든 코드 로 customer 대상 의 속성 을 정의 하 는 것 을 포함한다.그러나 이것 은 허구의 customer 대상 일 뿐 필요 하 다 면 다른 속성 을 추가 할 수 있다.상업 논리 층 에는 추가,업데이트,찾기 등 방법 도 포함 된다.
비 즈 니스 논리 층 은 GUI 층 과 데이터 액세스 층 사이 에 있 는 중간 층 이다.그 는 데이터 액세스 층 을 가리 키 는 인용 cusData=new DACustomer()가 있 고 System.Data 이름 공간 도 인용 했다.비 즈 니스 논리 층 은 DataSet 을 사용 하여 GUI 층 에 데 이 터 를 되 돌려 줍 니 다.
 


 
using System;
using System.Data;
namespace _3tierarchitecture
{
///
/// Summary description for BOCustomer.
///
public class BOCustomer
{
//Customer properties
private String fName;
private String lName;
private String cusId;
private String address;
private String tel;
private DACustomer cusData;
public BOCustomer()
{
//An instance of the Data access layer!
cusData = new DACustomer();
}
///
/// Property FirstName (String)
///
public String FName
{
get
{
return this.fName;
}
set
{
try
{
this.fName = value;
if (this.fName == "")
{
throw new Exception(
"Please provide first name ...");
}
}
catch(Exception e)
{
throw new Exception(e.Message.ToString());
}
}
}
///
/// Property LastName (String)
///
public String LName
{
get
{
return this.lName;
}
set
{
//could be more checkings here eg revmove ' chars
//change to proper case
//blah blah
this.lName = value;
if (this.LName == "")
{
throw new Exception("Please provide name ...");
}
}
}
///
/// Property Customer ID (String)
///
public String cusID
{
get
{
return this.cusId;
}
set
{
this.cusId = value;
if (this.cusID == "")
{
throw new Exception("Please provide ID ...");
}
}
}
///
/// Property Address (String)
///
public String Address
{
get
{
return this.address;
}
set
{
this.address = value; if (this.Address == "")
{
throw new Exception("Please provide address ...");
}
}
}
///
/// Property Telephone (String)
///
public String Tel
{
get
{
return this.tel;
}
set
{
this.tel = value;
if (this.Tel == "")
{
throw new Exception("Please provide Tel ...");
}
}
}
///
/// Function Add new customer. Calls
/// the function in Data layer.
///
public void Add()
{
cusData.Add(this);
}
///
/// Function Update customer details.
/// Calls the function in Data layer.
///
public void Update()
{
cusData.Update(this);
}
///
/// Function Find customer. Calls the
/// function in Data layer.
/// It returns the details of the customer using
/// customer ID via a Dataset to GUI tier.
///
public DataSet Find(String str)
{
if (str == "")
throw new Exception("Please provide ID to search");
DataSet data = null;
data = cusData.Find(str);
return data;
}
}
}
 
데이터 액세스 계층
데이터 계층 은 MS Access 데이터 베 이 스 를 처리 하 는 세부 사항 을 포함한다.이 모든 세부 사항 은 투명 해서 상업 논리 층 에 영향 을 주지 않 는 다.데이터 액세스 층 에는 비 즈 니스 논리 층 을 가리 키 는 인용 BOCustomer cus 가 있 습 니 다.응용 이 편리 하고 다른 데이터 베 이 스 를 지원 하기 위해 서 입 니 다.
 
using System;
using System.Data.OleDb;
using System.Data;
namespace _3tierarchitecture
{
///
/// Summary description for DACustomer.
///
public class DACustomer
{
private OleDbConnection cnn;
//change connection string as per the
//folder you unzip the files
private const string CnnStr =
"Provider=Microsoft.Jet.OLEDB.4.0;Data " +
"Source= D:\\Rahman_Backup\\Programming\\" +
"Csharp\\3tierarchitecture\\customer.mdb;";
//local variables
private String strTable="";
private String strFields="";
private String strValues="";
private String insertStr="";
//this needs to be changed based on customer
//table fields' Name of the database!
private const String thisTable = "tblCustomer";
private const String cus_ID = "CUS_ID";
private const String cus_LName = "CUS_L_NAME";
private const String cus_FName = "CUS_F_NAME";
private const String cus_Tel = "CUS_TEL";
private const String cus_Address = "CUS_ADDRESS";
public DACustomer()
{
} public DACustomer(BOCustomer cus)
{
// A reference of the business object class
}
//standard dataset function that adds a new customer
public void Add(BOCustomer cus)
{
String str = BuildAddString(cus);
OpenCnn();
//Open command option - cnn parameter is imporant
OleDbCommand cmd = new OleDbCommand(str,cnn);
//execute connection
cmd.ExecuteNonQuery();
// close connection
CloseCnn();
}
//standard dataset function that updates
//details of a customer based on ID
public void Update(BOCustomer cus)
{
OpenCnn();
String selectStr = "UPDATE " + thisTable +
" set " + cus_LName + " = '" + cus.LName + "'" +
", " + cus_FName + " = '" + cus.FName + "'" +
", " + cus_Address + " = '" + cus.Address + "'" +
", " + cus_Tel + " = '" + cus.Tel + "'" +
" where cus_ID = '" + cus.cusID + "'";
OleDbCommand cmd = new OleDbCommand(selectStr,cnn);
cmd.ExecuteNonQuery();
CloseCnn();
}
//standard dataset function that finds and
//return the detail of a customer in a dataset
public DataSet Find(String argStr)
{
DataSet ds=null;
try
{
OpenCnn();
String selectStr = "select * from " + thisTable +
" where cus_ID = '" + argStr + "'";
OleDbDataAdapter da =
new OleDbDataAdapter(selectStr,cnn);
ds = new DataSet();
da.Fill(ds,thisTable);
CloseCnn();
}
catch(Exception e)
{
String Str = e.Message;
}
return ds;
}
private void OpenCnn()
{
// initialise connection
String cnnStr = CnnStr;
cnn = new OleDbConnection(cnnStr);
// open connection
cnn.Open();
}
private void CloseCnn()
{
// 5- step five
cnn.Close();
}
// just a supporting function that builds
// and return the insert string for dataset.
private String BuildAddString(BOCustomer cus)
{
// these are the constants as
// set in the top of this module.
strTable="Insert into " + thisTable;
strFields=" (" + cus_ID +
"," + cus_LName +
"," + cus_FName +
"," + cus_Address +
"," + cus_Tel + ")";
//these are the attributes of the
//customer business object.
strValues= " Values ( '" + cus.cusID +
"' , '" + cus.LName +
"' , '" + cus.FName +
"' , '" + cus.Address +
"' , '" + cus.Tel + "' )";
insertStr = strTable + strFields + strValues;
return insertStr;
}
}
}

좋은 웹페이지 즐겨찾기