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

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

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

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

1.分析
在我们这个程序中采用如下的层次:Web层,业务实体层,数据层。
其中:
业务实体层负责Web层与数据层之间的数据交换。
数据层仅仅代表数据库。
Web层通过业务实体层来访问数据库。
我们的中间的业务实体层采用WebService.
2.实例
我们通过一个实例来学习三层架构。
(1)       以sql2000为例
建立TestUser数据库。
表的sql脚本(在查询分析器中执行即可):
/******Object: Table[dbo].[Customers]   ScriptDate:2004-01-080:46:35******/
CREATETABLE[dbo].[Customers](
   [CustomerID][int]IDENTITY(1,1)NOTNULL,
   [CustomerName][char](20)NOTNULL,
   [addr][varchar](50)NULL,
   [city][char](20)NULL,
   [phone][char](20)NULL,
   [fax][char](10)NULL
)ON[PRIMARY]
GO
 
/******Object: Table[dbo].[Users]   ScriptDate:2004-01-080:46:36******/
CREATETABLE[dbo].[Users](
   [ID][int]IDENTITY(1,1)NOTNULL,
   [TrueName][char](20)NOTNULL,
   [RegName][char](20)NOTNULL,
   [Pwd][char](10)NOTNULL,
   [Sex][char](2)NULL,
   [Email][char](20)NULL
)ON[PRIMARY]
GO
 
ALTERTABLE[dbo].[Customers]WITHNOCHECKADD
   CONSTRAINT[PK_Customers]PRIMARYKEY NONCLUSTERED
   (
       [CustomerID]
   ) ON[PRIMARY]
GO
 
ALTERTABLE[dbo].[Users]WITHNOCHECKADD
   CONSTRAINT[PK_Users]PRIMARYKEY NONCLUSTERED
   (
       [ID]
   ) ON[PRIMARY]
GO
 
(2)创建业务实体层
1.打开vs.net2002,新建一个项目,选Asp.NETWeb服务,位置是:http://localhost/mydotnet/tiner/WebData/
2.WebService的代码
usingSystem;
usingSystem.Collections;
usingSystem.ComponentModel;
usingSystem.Data;
usingSystem.Data.SqlClient; 
usingSystem.Diagnostics;
usingSystem.Web;
usingSystem.Web.Services;
usingSystem.Web.UI;
usingSystem.Web.UI.WebControls;
usingSystem.Web.UI.HtmlControls;
 
namespaceWebData
{
   ///<summary>
   ///Service1的摘要说明。
   ///</summary>
   [WebService(Namespace="http://www.ourfly.com",Description="<fontsize=4color='#FF6633'><b><br><center>使用C#写的三层架构的程序。</center></b><br><br></font>")]
   publicclassService1:System.Web.Services.WebService
   {
       SqlDataAdapterMyAdapter;
       stringstrConn="datasource=localhost;initialcatalog=TestUser;uid=sa;pwd=";
               
       publicService1()
       {
           //CODEGEN:该调用是ASP.NETWeb服务设计器所必需的
           InitializeComponent();
       }
 
       #regionComponentDesignergeneratedcode
       
       //Web服务设计器所必需的
       privateIContainercomponents=null;
               
       ///<summary>
       ///设计器支持所需的方法-不要使用代码编辑器修改
       ///此方法的内容。
       ///</summary>
       privatevoidInitializeComponent()
       {
       }
 
       ///<summary>
       ///清理所有正在使用的资源。
       ///</summary>
       protectedoverridevoidDispose(booldisposing)
       {
           if(disposing&&components!=null)
           {
               components.Dispose();
           }
           base.Dispose(disposing);       
       }
       
       #endregion
 
//定义一个私有方法,用来判断用户是否存在
       privateBooleanBoolReg(stringstrRegName)
       {
           BooleanstrResult;
           SqlConnectioncn;
           SqlCommandcmd;
           
           stringstrSQL;
           cn=new SqlConnection(strConn);
           cn.Open();
           
           strSQL="selectcount(*)fromUserswhereRegName='"+strRegName+"'";
           cmd=newSqlCommand(strSQL,cn);
           
           SqlDataReaderreader=cmd.ExecuteReader();
           reader.Read();
           inti=reader.GetInt32(0);
           if(i>0)
           {  
               reader.Close();
               cn.Close();
               strResult=true;
           }
           else
           {
               reader.Close();
               cn.Close();
               strResult=false;
           }
   
           returnstrResult;
       }
 
       [WebMethod(Description="完成用户注册功能.")]
       publicstringRegUser(stringstrTrueName,stringstrRegName,stringstrPwd,stringstrSex,stringstrEmail)
       {
           stringstrResult;
           SqlConnectioncn;
           SqlCommandcmd;
           
           //判断用户是否存在
           if(BoolReg(strRegName))
                 {
                     strResult="这个用户已经存在,请重新注册";
                     returnstrResult;
                 }
           else
           {
               stringstrSQL;
               cn=new SqlConnection(strConn);
               cn.Open();
           
               strSQL="insertintoUsers(TrueName,RegName,Pwd,Sex,Email)values('";
               strSQL+=strTrueName+"','";
               strSQL+=strRegName+"','";
               strSQL+=strPwd+"','";
               strSQL+=strSex+"','";
               strSQL+=strEmail+"')";
 
               cmd=newSqlCommand(strSQL,cn);
                   
               try
               {
                   cmd.ExecuteNonQuery();
                   cn.Close();
                   strResult="用户注册成功";
               }
               catch(Exceptione)
               {
                   cn.Close();
                   strResult="请仔细检查你的输入项";
               }
           }
           returnstrResult;
   
       }
 
       [WebMethod(Description="用户登录")]
       publicstringLogin(stringstrRegName,stringstrPwd)
       {
           SqlConnectioncn;
           SqlDataAdapterda;
           DataSetds;
           stringstrSQL,strResult;
           
           strSQL="selectTrueName,RegName,PwdfromUsers whereRegName='"+strRegName+"'andPwd='"+strPwd+"'";
           
           cn=newSqlConnection(strConn);
           cn.Open();
 
           da=newSqlDataAdapter(strSQL,cn);
           ds=newDataSet();
           da.Fill(ds,"Users");
 
           if(ds.Tables["Users"].Rows.Count>0)
           {
               strResult="登录成功";
 
           }
           else
           {
               strResult="用户名或口令有误或者没有这个用户!请重新输入!";
   
           }
           cn.Close();
           returnstrResult;
       }
 
 
       [WebMethod(Description="得到数据集.")]
       publicDataSetGetDataSet()
       {
           SqlConnectioncn;
           cn=newSqlConnection(strConn);
           stringstrSel="select*fromCustomers";
           cn.Open();
           MyAdapter=newSqlDataAdapter(strSel,strConn);
           DataSetds=newDataSet();
           MyAdapter.Fill(ds,"Customers");
           returnds;
       }
   }
}
 
运行后如下图所示:
 
 
(3)Web表现层
打开vs.net2002,新建一个项目,选Asp.NETWeb应用程序,位置是:”,选择”添加Web引用”,输入 添加引用后,如下图:
 
好了,我们开始写代码,详细代码如下:
usingSystem;
usingSystem.Collections;
usingSystem.ComponentModel;
usingSystem.Data;
usingSystem.Drawing;
usingSystem.Web;
usingSystem.Web.SessionState;
usingSystem.Web.UI;
usingSystem.Web.UI.WebControls;
usingSystem.Web.UI.HtmlControls;
usingSystem.Data.SqlClient;
 
namespacetiner
{
    ///<summary>
    ///WebForm1的摘要说明。
    ///</summary>
    publicclassWebForm1:System.Web.UI.Page
    {
        protectedSystem.Web.UI.WebControls.LabelLabel1;
        protectedSystem.Web.UI.WebControls.DataGridDataGrid1;
        protectedSystem.Web.UI.WebControls.LabelLabel2;
        protectedSystem.Web.UI.WebControls.LabelLabel3;
        protectedSystem.Web.UI.WebControls.TextBoxTxtUserName;
        protectedSystem.Web.UI.WebControls.ButtonBtLogin;
        protectedSystem.Web.UI.WebControls.ButtonBtReg;
        protectedSystem.Web.UI.WebControls.PanelPanel1;
        protectedSystem.Web.UI.WebControls.LabelLabel4;
        protectedSystem.Web.UI.WebControls.LabelLabel5;
        protectedSystem.Web.UI.WebControls.TextBoxTxtTrueName;
        protectedSystem.Web.UI.WebControls.LabelLabel6;
        protectedSystem.Web.UI.WebControls.LabelLabel7;
        protectedSystem.Web.UI.WebControls.LabelLabel8;
        protectedSystem.Web.UI.WebControls.ButtonBtOK;
        protectedSystem.Web.UI.WebControls.TextBoxTxtRegName;
        protectedSystem.Web.UI.WebControls.TextBoxTxtPwd;
        protectedSystem.Web.UI.WebControls.DropDownListDropDownListSex;
        protectedSystem.Web.UI.WebControls.TextBoxTxtEmail;
        protectedSystem.Web.UI.WebControls.TextBoxTxtPassword;
    
        stringmyResult;
        DataSetds;
        localhost.Service1myService=newlocalhost.Service1();
 
        privatevoidPage_Load(objectsender,System.EventArgse)
        {
             //在此处放置用户代码以初始化页面
             if(!Page.IsPostBack)
             {
                  Panel1.Visible=false;
             }
        }
 
        #regionWebFormDesignergeneratedcode
        overrideprotectedvoidOnInit(EventArgse)
        {
             //
             //CODEGEN:该调用是ASP.NETWeb窗体设计器所必需的。
             //
             InitializeComponent();
             base.OnInit(e);
        }
        
        ///<summary>
        ///设计器支持所需的方法-不要使用代码编辑器修改
        ///此方法的内容。
        ///</summary>
        privatevoidInitializeComponent()
        {   
             this.BtLogin.Click+=newSystem.EventHandler(this.BtLogin_Click);
             this.BtReg.Click+=newSystem.EventHandler(this.BtReg_Click);
             this.BtOK.Click+=newSystem.EventHandler(this.BtOK_Click);
             this.Load+=newSystem.EventHandler(this.Page_Load);
 
        }
        #endregion
 
 
 
        privatevoidBtReg_Click(objectsender,System.EventArgse)
        {
             DataGrid1.Visible=false;
             Panel1.Visible=true;
        }
 
        privatevoidBtLogin_Click(objectsender,System.EventArgse)
        {
             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="用户名或口令有误或者没有这个用户!请重新输入!";
             }
        }
 
        privatevoidBtOK_Click(objectsender,System.EventArgse)
        {
            myResult=myService.RegUser(TxtTrueName.Text,TxtRegName.Text,TxtPwd.Text,DropDownListSex.SelectedItem.Text,TxtEmail.Text);
             if(myResult.ToString()=="用户注册成功")
             {
                  Label1.Text="用户注册成功,可以登录查看信息";
                  return;
             }
             elseif(myResult.ToString()=="这个用户已经存在,请重新注册")
             {
                  Label1.Text="这个用户已经存在,请重新注册";
                  return;
             }
             else
             {
                  Label1.Text="用户注册发生错误,请检查每一项";
                  return;
             }
 
        }
 
    }
}
运行启动,输入正确的用户名和密码,点击”登录”按钮,会看到下面的界面:
 
点击”注册新用户”,出现注册界面,如果注册的用户存在,会产生提示:
 
总结:
Web表示层上完全没有数据库连接操作,它与数据库的连接任务是通过业务层来完成的,这样,程序的结构更加清晰。当然,程序中可以增加其它的层,如:业务规则层等。
如果错误,欢迎大家指教。
高效的学习 = 丰富的资料 + 积极的提问
阅读本文后,如有任何疑问和见解请直接在此提出,共同探讨。
posted @ 2005-11-19 18:45  torome  阅读(715)  评论(0)    收藏  举报