torome

如何使用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的代码="timesnewroman">="timesnewroman">
usingSystem;
usingSystem.Collections;=left>
=arial>
=4>=center>
usingSystem.ComponentModel;=left>
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;
       }
   }
}
 ="timesnewroman">
运行后如下图所示:
 ="timesnewroman">
 ="miter">="iflinedrawnpixellinewidth0">="sum@010">="sum00@1">="prod@212">="prod@321600pixelwidth">="prod@321600pixelheight">="sum@001">="prod@612">="prod@721600pixelwidth">="sum@8216000">="prod@721600pixelheight">="sum@10216000">="rect"gradientshapeok="t"o:extrusionok="f">="t"v:ext="edit">=_x0000_t75stroked="f"filled="f"path="m@4@5l@4@11@9@11@9@5xe"o:preferrelative="t"o:spt="75"coordsize="21600,21600">=""hspace=0src=">=_x0000_i1025style="width:415.5pt;height:299.25pt"type="#_x0000_t75">=en-usstyle="font-size:10.5pt;font-family:\'timesnewroman\';mso-bidi-font-size:12.0pt;mso-fareast-font-family:宋体;mso-font-kerning:1.0pt;mso-ansi-language:en-us;mso-fareast-language:zh-cn;mso-bidi-language:ar-sa">="timesnewroman">
(3)Web表现层="timesnewroman">
打开vs.net2002,新建一个项目,选Asp.NETWeb应用程序,位置是:”,选择”添加Web引用”,输入 =_x0000_t75stroked="f"filled="f"path="m@4@5l@4@11@9@11@9@5xe"o:preferrelative="t"o:spt="75"coordsize="21600,21600">添加引用后,如下图:="http:>="timesnewroman">="timesnewroman">="timesnewroman">="timesnewroman">="http:>
 ="miter">="iflinedrawnpixellinewidth0">="sum@010">="sum00@1">="prod@212">="prod@321600pixelwidth">="prod@321600pixelheight">="sum@001">="prod@612">="prod@721600pixelwidth">="sum@8216000">="prod@721600pixelheight">="sum@10216000">="rect"gradientshapeok="t"o:extrusionok="f">="t"v:ext="edit">=_x0000_t75stroked="f"filled="f"path="m@4@5l@4@11@9@11@9@5xe"o:preferrelative="t"o:spt="75"coordsize="21600,21600">=""hspace=0src=">=_x0000_i1025style="width:214.5pt;height:330.75pt"type="#_x0000_t75">=en-usstyle="font-size:10.5pt;font-family:\'timesnewroman\';mso-bidi-font-size:12.0pt;mso-fareast-font-family:宋体;mso-font-kerning:1.0pt;mso-ansi-language:en-us;mso-fareast-language:zh-cn;mso-bidi-language:ar-sa">
好了,我们开始写代码,详细代码如下:
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);

分类:

技术点:

相关文章: