如何使用C#創建一個3層的數據庫應用程序
發表時間:2024-06-20 來源:明輝站整理相關軟件相關文章人氣:
[摘要]如何使用C#創建一個三層的數據庫應用程序1.分析在我們這個程序中采用如下的層次:Web層,業務實體層,數據層。其中:業務實體層負責Web層與數據層之間的數據交換。數據層僅僅代表數據庫。Web層通過業務實體層來訪問數據庫。我們的中間的業務實體層采用WebService.2.實例我們通過一個實例來學習...
如何使用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 窗體設計器所必需的。
//
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表示層上完全沒有數據庫連接操作,它與數據庫的連接任務是通過業務層來完成的,這樣,程序的結構更加清晰。當然,程序中可以增加其它的層,如:業務規則層等。
如果