您的位置:首页 > 数据库

如何使用C#创建一个三层的数据库应用程序

2004-01-08 11:38 1216 查看

如何使用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表示层上完全没有数据库连接操作,它与数据库的连接任务是通过业务层来完成的,这样,程序的结构更加清晰。当然,程序中可以增加其它的层,如:业务规则层等。
如果错误,欢迎大家指教。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: