如何使用C#建立一個三層的資料庫應用程式
最後更新:2017-02-28
來源:互聯網
上載者:User
程式|建立|資料|資料庫 如何使用C#建立一個三層的資料庫應用程式
1.分析
在我們這個程式中採用如下的層次:Web層,業務實體層,資料層。
其中:
業務實體層負責Web層與資料層之間的資料交換。
資料層僅僅代表資料庫。
Web層通過業務實體層來訪問資料庫。
我們的中間的業務實體層採用WebService.
2.執行個體
我們通過一個執行個體來學習三層架構。
(1) 以sql2000為例
建立TestUser資料庫。
表的sql指令碼(在查詢分析器中執行即可):
/****** Object: Table [dbo].[Customers] Script Date: 2004-01-08 0:46:35 ******/
CREATE TABLE [dbo].[Customers] (
[CustomerID] [int] IDENTITY (1, 1) NOT NULL ,
[CustomerName] [char] (20) NOT NULL ,
[addr] [varchar] (50) NULL ,
[city] [char] (20) NULL ,
[phone] [char] (20) NULL ,
[fax] [char] (10) NULL
) ON [PRIMARY]
GO
/****** Object: Table [dbo].[Users] Script Date: 2004-01-08 0:46:36 ******/
CREATE TABLE [dbo].[Users] (
[ID] [int] IDENTITY (1, 1) NOT NULL ,
[TrueName] [char] (20) NOT NULL ,
[RegName] [char] (20) NOT NULL ,
[Pwd] [char] (10) NOT NULL ,
[Sex] [char] (2) NULL ,
[Email] [char] (20) NULL
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[Customers] WITH NOCHECK ADD
CONSTRAINT [PK_Customers] PRIMARY KEY NONCLUSTERED
(
[CustomerID]
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[Users] WITH NOCHECK ADD
CONSTRAINT [PK_Users] PRIMARY KEY NONCLUSTERED
(
[ID]
) ON [PRIMARY]
GO
(2)建立業務實體層
1.開啟vs.net2002,建立一個項目,選Asp.NET Web服務,位置是: http://localhost/mydotnet/tiner/WebData/
2.WebService的代碼
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Web;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
namespace WebData
{
/// <summary>
/// Service1 的摘要說明。
/// </summary>
[WebService (Namespace = "http://www.ourfly.com", Description = "<font size=4 color='#FF6633'><b><br><center>使用C#寫的三層架構的程式。</center></b><br><br></font>")]
public class Service1 : System.Web.Services.WebService
{
SqlDataAdapter MyAdapter;
string strConn="data source=localhost;initial catalog=TestUser;uid=sa;pwd=";
public Service1()
{
//CODEGEN:該調用是 ASP.NET Web 服務設計器所必需的
InitializeComponent();
}
#region Component Designer generated code
//Web 服務設計器所必需的
private IContainer components = null;
/// <summary>
/// 設計器支援所需的方法 - 不要使用代碼編輯器修改
/// 此方法的內容。
/// </summary>
private void InitializeComponent()
{
}
/// <summary>
/// 清理所有正在使用的資源。
/// </summary>
protected override void Dispose( bool disposing )
{
if(disposing && components != null)
{
components.Dispose();
}
base.Dispose(disposing);
}
#endregion
//定義一個私人方法,用來判斷使用者是否存在
private Boolean BoolReg(string strRegName)
{
Boolean strResult;
SqlConnection cn;
SqlCommand cmd;
string strSQL;
cn=new SqlConnection(strConn);
cn.Open();
strSQL="select count(*) from Users where RegName='"+strRegName+"'";
cmd=new SqlCommand(strSQL,cn);
SqlDataReader reader = cmd.ExecuteReader();
reader.Read();
int i = reader.GetInt32(0);
if (i>0)
{
reader.Close();
cn.Close ();
strResult= true;
}
else
{
reader.Close();
cn.Close ();
strResult=false;
}
return strResult;
}
[WebMethod(Description="完成使用者註冊功能.")]
public string RegUser(string strTrueName,string strRegName,string strPwd,string strSex,string strEmail)
{
string strResult;
SqlConnection cn;
SqlCommand cmd;
//判斷使用者是否存在
if (BoolReg(strRegName))
{
strResult="這個使用者已經存在,請重新註冊";
return strResult;
}
else
{
string strSQL;
cn=new SqlConnection(strConn);
cn.Open();
strSQL="insert into Users (TrueName,RegName,Pwd,Sex,Email) values( '";
strSQL+=strTrueName+"','";
strSQL+=strRegName+"','";
strSQL+=strPwd+"','";
strSQL+=strSex+"','";
strSQL+=strEmail+"')";
cmd=new SqlCommand(strSQL,cn);
try
{
cmd.ExecuteNonQuery();
cn.Close ();
strResult= "使用者註冊成功";
}
catch(Exception e)
{
cn.Close ();
strResult="請仔細檢查你的輸入項";
}
}
return strResult;
}
[WebMethod(Description="使用者登入")]
public string Login(string strRegName,string strPwd)
{
SqlConnection cn;
SqlDataAdapter da;
DataSet ds;
string strSQL,strResult;
strSQL="select TrueName,RegName,Pwd from Users where RegName='"+strRegName+"' and Pwd='"+strPwd+"'";
cn=new SqlConnection(strConn);
cn.Open();
da=new SqlDataAdapter(strSQL,cn);
ds=new DataSet();
da.Fill(ds,"Users");
if(ds.Tables["Users"].Rows.Count>0)
{
strResult= "登入成功";
}
else
{
strResult= "使用者名稱或口令有誤或者沒有這個使用者!請重新輸入!";
}
cn.Close();
return strResult;
}
[WebMethod(Description="得到資料集.")]
public DataSet GetDataSet()
{
SqlConnection cn;
cn=new SqlConnection(strConn);
string strSel="select * from Customers";
cn.Open();
MyAdapter=new SqlDataAdapter(strSel,strConn);
DataSet ds=new DataSet();
MyAdapter.Fill(ds,"Customers");
return ds;
}
}
}
運行後如下圖所示:
(3)Web表現層
開啟vs.net2002,建立一個項目,選Asp.NET Web應用程式,位置是: http://localhost/mydotnet/tiner/WebApplication1
在方案總管中,右鍵點擊”引用”,選擇”添加Web引用”, 輸入http://localhost/mydotnet/tiner/WebData/Service1.asmx如下圖所示:
添加引用後,如下圖:
好了,我們開始寫代碼,詳細代碼如下:
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
namespace tiner
{
/// <summary>
/// WebForm1 的摘要說明。
/// </summary>
public class WebForm1 : System.Web.UI.Page
{
protected System.Web.UI.WebControls.Label Label1;
protected System.Web.UI.WebControls.DataGrid DataGrid1;
protected System.Web.UI.WebControls.Label Label2;
protected System.Web.UI.WebControls.Label Label3;
protected System.Web.UI.WebControls.TextBox TxtUserName;
protected System.Web.UI.WebControls.Button BtLogin;
protected System.Web.UI.WebControls.Button BtReg;
protected System.Web.UI.WebControls.Panel Panel1;
protected System.Web.UI.WebControls.Label Label4;
protected System.Web.UI.WebControls.Label Label5;
protected System.Web.UI.WebControls.TextBox TxtTrueName;
protected System.Web.UI.WebControls.Label Label6;
protected System.Web.UI.WebControls.Label Label7;
protected System.Web.UI.WebControls.Label Label8;
protected System.Web.UI.WebControls.Button BtOK;
protected System.Web.UI.WebControls.TextBox TxtRegName;
protected System.Web.UI.WebControls.TextBox TxtPwd;
protected System.Web.UI.WebControls.DropDownList DropDownListSex;
protected System.Web.UI.WebControls.TextBox TxtEmail;
protected System.Web.UI.WebControls.TextBox TxtPassword;
string myResult;
DataSet ds;
localhost.Service1 myService =new localhost.Service1();
private void Page_Load(object sender, System.EventArgs e)
{
// 在此處放置使用者代碼以初始化頁面
if ( !Page.IsPostBack )
{
Panel1.Visible =false;
}
}
#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN:該調用是 ASP.NET Web Form設計器所必需的。
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// 設計器支援所需的方法 - 不要使用代碼編輯器修改
/// 此方法的內容。
/// </summary>
private void InitializeComponent()
{
this.BtLogin.Click += new System.EventHandler(this.BtLogin_Click);
this.BtReg.Click += new System.EventHandler(this.BtReg_Click);
this.BtOK.Click += new System.EventHandler(this.BtOK_Click);
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
private void BtReg_Click(object sender, System.EventArgs e)
{
DataGrid1.Visible =false;
Panel1.Visible =true;
}
private void BtLogin_Click(object sender, System.EventArgs e)
{
if (TxtUserName.Text =="" || TxtPassword.Text=="")
{
Label1.Text ="請輸入使用者名稱或者密碼";
return;
}
DataGrid1.Visible =true;
Panel1.Visible =false;
myResult=myService.Login(TxtUserName.Text,TxtPassword.Text ) ;
if (myResult.ToString() =="登入成功")
{
ds=myService.GetDataSet();
DataGrid1.DataSource =ds.Tables["Customers"];
DataGrid1.DataBind();
}
else
{
Label1.Text ="使用者名稱或口令有誤或者沒有這個使用者!請重新輸入!";
}
}
private void BtOK_Click(object sender, System.EventArgs e)
{
myResult=myService.RegUser(TxtTrueName.Text,TxtRegName.Text,TxtPwd.Text,DropDownListSex.SelectedItem.Text ,TxtEmail.Text);
if(myResult.ToString()=="使用者註冊成功" )
{
Label1.Text ="使用者註冊成功,可以登入查看資訊";
return;
}
else if(myResult.ToString()=="這個使用者已經存在,請重新註冊" )
{
Label1.Text ="這個使用者已經存在,請重新註冊";
return;
}
else
{
Label1.Text ="使用者註冊發生錯誤,請檢查每一項";
return;
}
}
}
}
運行啟動,輸入正確的使用者名稱和密碼,點擊”登入”按鈕,會看到下面的介面:
點擊”註冊新使用者”,出現註冊介面,如果註冊的使用者存在,會產生提示:
總結:
Web展示層上完全沒有資料庫連接操作,它與資料庫的串連任務是通過業務層來完成的,這樣,程式的結構更加清晰。當然,程式中可以增加其它的層,如:商務規則層等。
如果錯誤,歡迎大家指教。