一般处理程序加简单三层实现增删查改(2)

接下来我创建Dal(数据访问层)创建一个StudentManagement_DAL.cs类文件,直接上代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace StudentManagement.DAL
{
    using StudentManagement.Model;
    using System.Data.SqlClient;
    using System.Data;
  public  class StudentManagement_DAL
    {
      
      //新增
      public int Add(SM_Class sc) {
          string str = "insert SM_Class values(@SM_name,@SM_Grade,@SM_Class,@SM_Gender,@SM_Age,@SM_OutTime,@SM_Istf)";
    
          SqlParameter[] sqlpmt = new SqlParameter[]{
          new SqlParameter("@SM_name",sc.SM_Name),
          new SqlParameter("@SM_Grade",sc.SM_Grade),
          new SqlParameter("@SM_Class",sc.SM_Classes),
          new SqlParameter("@SM_Gender",sc.SM_Gender),
          new SqlParameter("@SM_Age",sc.SM_Age),
          new SqlParameter("@SM_OutTime",sc.SM_OutTime),
          new  SqlParameter("@SM_Istf",1)
          };
           return     HelperSQL.ExecuteCommand(str,sqlpmt); 
      }

      //软删除
      public int Deleter(int ID) {
          string str = "Update SM_Class set SM_Istf=0 where SM_id=@ID";
          SqlParameter[] sqlpmt = new SqlParameter[]{
          new SqlParameter("@ID",ID)
          };
          return HelperSQL.ExecuteCommand(str, sqlpmt);    
      }
      /// <summary>
      /// 查询所有数据
      /// </summary>
      /// <returns></returns>
      public DataSet QuerySM() {
          string str = "select * from SM_Class where SM_Istf=1 ";
          return HelperSQL.GetDataSet(str);
      }
      /// <summary>
      /// 更据id查询
      /// </summary>
      /// <param name="id"></param>
      /// <returns></returns>
      public DataSet QuerySM(int id) {
          string str = "select * from SM_Class where SM_id=@id";
          SqlParameter[] sqlpmt = new SqlParameter[]{
          new SqlParameter ("@id",id)
          };
          return HelperSQL.GetDataSet(str,sqlpmt);
      }
      //更新
      public int UpdateSM(SM_Class model) { 
      string str="UPDATE SM_Class SET  SM_name = @SM_name ,  SM_Grade = @SM_Grade ,SM_Class = @SM_Class ,SM_Gender = @SM_Gender ,SM_Age = @SM_Age  where SM_Id=@SM_Id  ";
      SqlParameter[] sqlpmt = new SqlParameter[]{
          new SqlParameter("@SM_name",model.SM_Name),
          new SqlParameter("@SM_Grade",model.SM_Grade),
          new SqlParameter("@SM_Class",model.SM_Classes),
          new SqlParameter("@SM_Gender",model.SM_Gender),
          new SqlParameter("@SM_Age",model.SM_Age),
        new SqlParameter ("@SM_Id",model.SM_ID)
          };
      return HelperSQL.ExecuteCommand(str, sqlpmt);
      }
    }
}
View Code

这里做个小小的说明,我的删除,不是硬删除,我是用的软删除,在我的数据库里有个SM_Istf的字段是用来判断这个数据是否删除用的。

查询,因为比较懒 所以就直接写了 select * from SM_Class where SM_Istf=0,这个做两个说明

第一,select 后面不应该写“*”,这个建议写上字段

第二,SM_Istf=0 是表示没有被删除,等于1表示删除,因为SM_Istf 在数据库我是用的bool类型表示的 在数据库 bit。

接着上bll(业务逻辑层的代码)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace StudentManagement.BLL
{
    using System.Data;
    using StudentManagement.Model;
   public class StudentManagement_BLL
    {
       StudentManagement.DAL.StudentManagement_DAL smd = new DAL.StudentManagement_DAL();
      
       //新增
       public int Add(SM_Class sc)
       {

           return smd.Add(sc);
       }

       //软删除
       public int Deleter(int ID)
       {
           return smd.Deleter(ID);
       }
       /// <summary>
       /// 查询所有数据
       /// </summary>
       /// <returns></returns>
       public DataSet QuerySM()
       {
           return smd.QuerySM();
       }
       /// <summary>
       /// 查询id号的数据
       /// </summary>
       /// <param name="id"></param>
       /// <returns></returns>
       public DataSet QuerySM(int id) {
           return smd.QuerySM(id);
       }
       //更新
       public int UpdateSM(SM_Class model)
       {
           return smd.UpdateSM(model);
       }
    }
}
View Code

接着上UI层代码

新建一个temp文件夹 存放html文件,注:没有写样式,为什么不写,因为没有没有美工妹子女朋友...

 

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
    <script type="text/javascript">
        function Del(id) {
            if (confirm("确定删除")) {
                window.location = "/Del.ashx?id=" + id;
            }
        }
    </script>
</head>
<body>
    <table>
        <tr>
            <th>id</th>
            <th>姓名</th>
            <th>班级</th>
            <th>年级</th>
            <th>性别</th>
            <th>年级</th>
            <th>时间</th>
            <th>操作</th>
        </tr>
        ${sb}
    </table>
</body>
</html>
View Code
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
</head>
<body>
    <form action="/update.ashx" method="post">
        <input type="hidden" id="id" name ="id" value="<%=id%>" />
       <table>
     <tr>
            <th>姓名</th>
            <td><input type="text" name="name" id="name" value ="<%=name %>" /></td>
            </tr>
        <tr>
            <th>班级</th>
            <td><input type="text" name="grade" id="Text1"  value="<%=grade %>"/></td>
            </tr>
        <tr>
            <th>年级</th>
            <td><input type="text" name="class" id="Text2"  value="<%=classes %>"/></td>
            </tr>
        <tr>
            <th>性别</th>
            <td>
                <input type="radio" name="gender" id="Text3" radio1  /><input type ="radio" name="gender" id="Text4" radio0  /></td>
            </tr>
        <tr>
            <th>年龄</th>
            <td><input type="text" name="age" id="Text5"  value="<%=age %>"/></td>
            </tr>
    
        <tr>
            <td>
                <input type="submit" value ="提交" />
                <input type="reset" value="重置" />
            </td>
        </tr>
           </table>
           </form>
</body>
</html>
View Code

这里面我用的替换占位符的方法,用一般处理程序读取html页面并且替换里面的占位符 ,占位符分别用了${sb},<%=%>,abc 这三种样式的占位

不多说了上一般处理程序的代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace HtmlAshx
{
    using StudentManagement.BLL;
    using StudentManagement.Model;
    using System.Data;
    /// <summary>
    /// query 的摘要说明
    /// </summary>
    public class query : IHttpHandler
    {
        StudentManagement_BLL smb = new StudentManagement_BLL();
        System.Text.StringBuilder sb=new System.Text.StringBuilder (200);
        public void ProcessRequest(HttpContext context)
        {
          
            //获得所有数据
             DataSet  ds=   smb.QuerySM();
            //得到路径
             string strpath = context.Server.MapPath("/temp/getquery.html");
            //得到路径下所有的内容
             string strtext = System.IO.File.ReadAllText(strpath);
            
            DataTable dt = ds.Tables[0];
            foreach (DataRow item in dt.Rows)
            {
                sb.Append(" <tr>");
                sb.Append(" <td>" + item["SM_id"] + "</td>");
                sb.Append(" <td>" + item["SM_name"] + "</td>");
                sb.Append(" <td>" + item["SM_Grade"] + "</td>");
                sb.Append(" <td>" + item["SM_Class"] + "</td>");
                sb.Append(" <td>" + item["SM_Gender"] + "</td>");
                sb.Append(" <td>" + item["SM_Age"] + "</td>");
                sb.Append(" <td>" + item["SM_OutTime"] + "</td>");
                sb.Append(" <td><a href='javascript:void(0)'  onclick='Del("+ item["SM_id"] +")'>删除</a>|<a href=\"update.ashx?id=" + item["SM_id"] + "\">编辑</td>");
                sb.Append(" </tr>");
            }
            //替换占位
            strtext = strtext.Replace("${sb}", sb.ToString());
            //响应回去
            context.Response.Write(strtext);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
View Code

这个上用来显示查询出来的结果代码

下一个删除

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace HtmlAshx
{
    using StudentManagement.BLL;

    /// <summary>
    /// del 的摘要说明
    /// </summary>
    public class del : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            StudentManagement_BLL smb = new StudentManagement_BLL();
            //获取传过来的id
            string id = context.Request.QueryString["id"];
            //验证参数是否为空
            if (string.IsNullOrEmpty(id))
            {
                context.Response.Write("<script>alert('id参数不对');window.location='/query.ashx'</script>");
                return;
            }
            //删除
            int i = smb.Deleter(int.Parse(id));
            if (i > 0)
            {
                context.Response.Write("<script>alert('删除成功');window.location='/query.ashx'</script>");
                return;
            }
            else
            {
                context.Response.Write("<script>alert('删除失败');window.location='/query.ashx'</script>");
                return;
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
View Code

再来一个编辑

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace HtmlAshx
{
    using StudentManagement.BLL;
    using System.Data;
    /// <summary>
    /// update 的摘要说明
    /// </summary>
    public class update : IHttpHandler
    {
        StudentManagement_BLL smb = new StudentManagement_BLL();
        StudentManagement.Model.SM_Class sc = new StudentManagement.Model.SM_Class();
        public void ProcessRequest(HttpContext context)
        {
            //获取html路径
            string strpath = context.Server.MapPath("/temp/update.html");
            //获取文件内容
            string sfile = System.IO.File.ReadAllText(strpath);
            //判断上get 还上post
            if (context.Request.HttpMethod.ToLower() == "get")
            {
                //获取url 上的id
                string id = context.Request.QueryString["id"];
                //获取内容
                DataSet ds = smb.QuerySM(int.Parse(id));
                DataTable dt = ds.Tables[0];
                //获取性别
                var str = dt.Rows[0]["SM_Gender"].ToString();
                //判断性别
                if (str == "")
                {
                    sfile = sfile.Replace("<%=name %>", dt.Rows[0]["SM_name"].ToString()).Replace("<%=grade %>", dt.Rows[0]["SM_Grade"].ToString()).Replace("<%=classes %>", dt.Rows[0]["SM_Class"].ToString()).Replace("<%=age %>", dt.Rows[0]["SM_Age"].ToString()).Replace("radio1", "value=\"男\" checked=\"checked\"").Replace("radio0 ", "value=\"女\" ").Replace("<%=id%>", id);
                }
                else
                {
                    sfile = sfile.Replace("<%=name %>", dt.Rows[0]["SM_name"].ToString()).Replace("<%=grade %>", dt.Rows[0]["SM_Grade"].ToString()).Replace("<%=classes %>", dt.Rows[0]["SM_Class"].ToString()).Replace("<%=age %>", dt.Rows[0]["SM_Age"].ToString()).Replace("radio0", "value=\"女 \" checked=\"checked\"").Replace("radio1", "value=\"男\" ").Replace("<%=id%>", id);
                }
                context.Response.Write(sfile);

            }
            else {
                //获取post传过来的值
                string id = context.Request.Form["id"];
                string name = context.Request.Form["name"];
                string grade = context.Request.Form["grade"];
                string classes = context.Request.Form["class"];
                string gender = context.Request.Form["gender"];
                string age = context.Request.Form["age"];
                sc.SM_Age =int.Parse( age);
                sc.SM_Name = name;
                sc.SM_Grade = grade;
                sc.SM_Classes = classes;
                sc.SM_Gender = gender;
                sc.SM_OutTime = DateTime.Now;
                sc.SM_ID =int.Parse( id);

             int i=   smb.UpdateSM(sc);
             if (i > 0)
             {
                 context.Response.Write("<script>alert('修改成功');window.location='/query.ashx'</script>");
                 context.Response.End();
             }
             else {
                 context.Response.Write("<script>alert('修改失败');window.location='/query.ashx'</script>");
                 context.Response.End();
             }
            }
            
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
View Code

所有的代码上传完毕

通过以上一般处理程序的增删查改总结

其实刚刚开始做的时候上用动态页面做的,后来发现不对,不上写的上一般程序么,怎么可以用动态页面做,后来之后只好改。

说明: html页面只是为了读取文件里面的代码,然后再一般处理程序中替换掉里面的占位符,响应给一般处理程序生成页面。这个应该算上大体的思路。

说下总结吧:

第一、这里面有比较纠结的事情,希望大神指点下,第一就是性别字段,我都上在内存dataset中读取数据库的表,因此我在model层的类中的字段和属性就没有什么用了,原本上在属性上做点手脚,可是后来发现我从数据库中读取数据到dataset中而没有转换成list<T>所以自己封装的属性性别值没有用上,可惜了点。

第二、还上html页面的 type=radio 这个东西的vlaue值 我比较的纠结 ,刚刚开始的时候我上用的0和1表示,后来写的编辑的时候发现不行,又在初始化页面的时候改成了“男”和“女”。

第三、在编辑的时候忘记把,id值给保存下来,在dal层的update中忘记写where条件。导致了我整个的数据库值全部修改。 后来的解决法案 在html中添加一个type="hidden" value="<%=id%>" 用来保存id的值,不然我的数据又出错了,在dal层中加上where判断条件。 

其他的好像没有什么东西可以说了 一般处理程序主要用途可能在生成验证码一类的懂,可能像我这样傻逼来写增删查改的估计也不会这么纠结。

其实好像用jquery的东西,或者上动态页面,也不用写的这么纠结,但是为了让自己像别人说的你基础太差了,所以我情愿多花点时间来写一般处理程序,虽然上代码可能不上那么简洁,可是还上能让自己动动脑子,可能就上写程序的快乐吧 。

好像下一步就上用动态页面加上一般处理程序来写一套增删查改....继续坚持!

 model层 (实体类层的代码)

using System;
using System.Collections.Generic;
using System.Text;


namespace StudentManagement.Model
{
    //序列化接口没有方法或字段,仅用于标识可序列化的语义
    [Serializable ()]
   public class SM_Class
    {
        //构成函数
        public SM_Class() { }
        private int SM_id;

        public int SM_ID
        {
            get { return SM_id; }
            set { SM_id = value; }
        }
        private string SM_name;

        public string SM_Name
        {
            get { return SM_name; }
            set { SM_name = value; }
        }
        private string SM_grade;

        public string SM_Grade
        {
            get { return SM_grade; }
            set { SM_grade = value; }
        }
        private string SM_class;

        public string SM_Classes
        {
            get { return SM_class; }
            set { SM_class = value; }
        }
        private string SM_gender;

        public string SM_Gender
        {
            set
            {
                SM_gender = value;
            }
            get
            {
                return SM_gender;
            }
        }

        private int SM_age;

        public int SM_Age
        {
            get { return SM_age; }
            set { SM_age = value; }
        }
        private DateTime SM_outTime;

        public DateTime SM_OutTime
        {
            get { return SM_outTime; }
            set { SM_outTime = value; }
        }
    }
}
View Code

 

posted @ 2014-12-29 15:21  与格律上  阅读(689)  评论(0编辑  收藏  举报