HttpHandler(一般處理程序)進行增刪改查

如果不是asp.net webform,怎麼進行增刪改查呢?
首先:
創建一個SqlHelper.cs

public class SqlHelper
    {
        public static readonly string conString = ConfigurationManager.ConnectionStrings["sqlCon"].ConnectionString;
        //增刪改
        public static bool ExeNonQuery(string sql, CommandType type, params SqlParameter[] lists)
        {
            bool bFlag = false;
            using (SqlConnection con = new SqlConnection(conString))
            {
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = con;
                cmd.CommandText = sql;
                cmd.CommandType = type;
                if (lists!=null)
                {
                    foreach (SqlParameter p in lists)
                    {
                        cmd.Parameters.Add(p);
                    }
                }
                try
                {
                    if (con.State == ConnectionState.Closed)
                    {
                        con.Open();
                    }
                    int result = cmd.ExecuteNonQuery();
                    if (result > 0)
                    {
                        bFlag = true;
                    }
                }
                catch { ;}
            }
            return bFlag;
        }
        //查.讀
        public static SqlDataReader ExeDataReader(string sql, CommandType type, params SqlParameter[] lists)
        {
            SqlConnection con = new SqlConnection(conString);
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = con;
            cmd.CommandText = sql;
            cmd.CommandType = type;
            if (con.State == ConnectionState.Closed)
            {
                con.Open();
            }
            if (lists!=null)
            {
                foreach (SqlParameter p in lists)
                {
                    cmd.Parameters.Add(p);
                }
            }
            SqlDataReader reader = cmd.ExecuteReader();
            return reader;
        }
        //返回單個值
        public static object GetScalar(string sql, CommandType type, params SqlParameter[] lists)
        {
            object returnValue = null;
            using (SqlConnection con = new SqlConnection(conString))
            {
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = con;
                cmd.CommandText = sql;
                cmd.CommandType = type;
                if (lists!=null)
                {
                    foreach (SqlParameter p in lists)
                    {
                        cmd.Parameters.Add(p);
                    }
                }
                try
                {
                    if (con.State == ConnectionState.Closed)
                    {
                        con.Open();
                    }
                    returnValue = cmd.ExecuteScalar();
                }
                catch { ; }
            }
            return returnValue;
        }
        //事務
        public static bool ExeNonQueryTran(List<SqlCommand> list)
        {
            bool flag = true;
            SqlTransaction tran = null;
            using (SqlConnection con = new SqlConnection(conString))
            {
                try
                {
                    if (con.State == ConnectionState.Closed)
                    {
                        con.Open();
                        tran = con.BeginTransaction();
                        foreach (SqlCommand com in list)
                        {
                            com.Connection = con;
                            com.Transaction = tran;
                            com.ExecuteNonQuery();
                        }
                        tran.Commit();
                    }
                }
                catch (Exception ex)
                {
                    Console.Write(ex.Message);
                    tran.Rollback();
                    flag = false;
                }
            }
            return flag;
        }
        //返回DataTable
        public static DataTable GetTable(string sql)
        {
            SqlConnection conn = new SqlConnection(conString);
            SqlDataAdapter da = new SqlDataAdapter(sql, conn);
            DataTable table = new DataTable();
            da.Fill(table);
            return table;
        }
                                                      
    }

然後再Web.Config裏面進行配置

<configuration>
  <connectionStrings>
    <add name="sqlCon" connectionString="server=.;database=student;uid=sa;pwd=fiybird"/>
  </connectionStrings>
    <system.web>
        <compilation debug="true" targetFramework="4.0" />
    </system.web>

將要操作的表stus
dO1RFo*HDgAA&bo=vwDrAAAAAAABAHM!&t=5&su=

創建一個html頁面List.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="JS/jquery-1.8.3.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(function () {
            $("a:contains('刪除')").click(function () {
                if (!confirm("你確定要刪除麼")) {
                    return false;
                }
            })
        })
    </script>
</head>
<body>
<table border="1" cellspacing="0" cellpadding="0" width="500">
<tr>
<th>編號</th>
        <th>姓名</th>
        <th>性別</th>
        <th>班級</th>
        <th>操作(刪除)</th>
        <th>操作(查看)</th>
        <th>操作(修改)</th>
</tr>
    {body}//這裏是不是看不懂,先別急,往下看
</table>
</body>
</html>
 接着創建一個一般處理程序List.ashx
public class List : IHttpHandler
    {
        public void Proce***equest(HttpContext context)
        {
            context.Response.ContentType = "text/html";
           // string path = context.Server.MapPath("List.html");
            string strHtml = Commd.getFile("List.html");
            context.Response.Write(strHtml.Replace("{body}", Getpost()));//把得到的數據和{body}進行替換
        }
        string Getpost()
        {
            StringBuilder sb = new StringBuilder();
            List<Stus> list = getAll();
            foreach (Stus stu in list)
            {
                sb.AppendFormat("<tr>");
                sb.AppendFormat("<td>" + stu.id + "</td>");
                sb.AppendFormat("<td>"+stu.name+"</td>");
                sb.AppendFormat("<td>" + stu.sex + "</td>");
                sb.AppendFormat("<td>" + stu.c_id + "</td>");
                sb.AppendFormat("<td><a href='Del.ashx?id={0}'>刪除</a></td>",stu.id);
                sb.AppendFormat("<td><a href='Dils.ashx?id={0}'>查看</a></td>", stu.id);
                sb.AppendFormat("<td><a href='Edit.ashx?id={0}'>修改</a></td>", stu.id);
                sb.AppendFormat("</tr>");
            }
            return sb.ToString();
        }
        public List<Stus> getAll()//查詢得到所有的數據
        {
            string sql=string.Format("select * from stus");
            List<Stus> list = new List<Stus>();
            IDataReader red = SqlHelper.ExeDataReader(sql, CommandType.Text, null);
            while (red.Read())
            {
                Stus s = new Stus
                {
                    id = int.Parse(red[0].ToString()),
                    name = red[1].ToString(),
                    sex = red[2].ToString(),
                    c_id = int.Parse(red[3].ToString())
                };
                list.Add(s);
            }
            return list;
        }
        public class Stus//創建類
        {
            public int id { get; set; }
            public string name { get; set; }
            public string sex { get; set; }
            public int c_id { get; set; }
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }

顯示效果:
dCrCqI8ZDwAA&bo=JwI2AQAAAAABADU!&t=5&su=
接着進行刪除操作處理:
創建一個Del.ashx處理刪除

public class Del : IHttpHandler
    {
        public void Proce***equest(HttpContext context)
        {
            context.Response.ContentType = "text/html";
            int id = int.Parse(context.Request["id"]);
                if(onDel(id))
                {
                    context.Response.Redirect("List.ashx");
                }
        }
        bool onDel(int id)
        {
            string sql = string.Format("delete from stus where id={0}",id);
            return SqlHelper.ExeNonQuery(sql, CommandType.Text, null);
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }

效果:
dIsvEI.VDwAA&bo=LQIXAQAAAAABAB4!&t=5&su=
dDSp5o2PDwAA&bo=AgLRAAAAAAABAPY!&t=5&su=
已經被刪除了
再接下來進行查看的操作,着裏要創建一個Dils.ashx和Dils.html
先看
Dils.html頁面

<table border="1" cellspacing="0" cellpadding="0" width="300">
<tr>
<th>編號</th>
        <th>姓名</th>
        <th>性別</th>
        <th>班級</th>
</tr>
    <tr>
        <td>{id}</td>
         <td>{name}</td>
          <td>{sex}</td>
          <td>{c_id}</td>
   </tr>
   <tr>
    <td colspan="4"><a href="List.ashx">返回</a></td>
   </tr>
</table>

然後Dils.ashx進行處理:

public class Dils : IHttpHandler
    {
        public void Proce***equest(HttpContext context)
        {
            context.Response.ContentType = "text/html";
            int id = int.Parse(context.Request["id"]);
            string strHtml = Commd.getFile("Dils.html");
            DataTable dt=getTable(id);
            strHtml = strHtml.Replace("{id}", dt.Rows[0]["id"].ToString());
            strHtml=strHtml.Replace("{name}",dt.Rows[0]["name"].ToString());
            strHtml=strHtml.Replace("{sex}",dt.Rows[0]["sex"].ToString());
            strHtml = strHtml.Replace("{c_id}", dt.Rows[0]["c_id"].ToString());
            context.Response.Write(strHtml);
        }
        DataTable getTable(int id)
        {
            string sql = string.Format("select id,name,sex,c_id from stus where id={0}",id);
            DataTable dt = SqlHelper.GetTable(sql);
            return dt;
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }

效果:
dDkDuozDDwAA&bo=aAFpAAAAAAABACc!&t=5&su=
最後來看看修改的操作:
這裏先建立一個Edit.html頁面:

<form action="EditPros.ashx" method="post">
    <table border="1" cellspacing="0" cellpadding="0" width="100%">
    <tr>
    <th>編號</th>
        <th>姓名</th>
        <th>性別</th>
        <th>班級</th>
    </tr>
        <tr>
            <td><input type="txt" name="id" value="{id}" disabled="disabled"  />
            <input type="hidden" name="id" value="{id}" />
            </td>
            <td><input type="txt" name="name" value="{name}" /></td>
            <td><input type="txt" name="sex" value="{sex}" /></td>
            <td><input type="txt" name="c_id" value="{c_id}" /></td>
        </tr>
        <tr>
            <td colspan="4">
            <input type="submit" value="提交"/>
            <input type="reset" value="重置"/>
            </td>
        </tr>
    </table>
</form>

然後創建Edit.ashx和 EditPros.ashx來進行處理
Edit.ashx處理跟Dils.ashx差不多

public class Dils : IHttpHandler
    {
        public void Proce***equest(HttpContext context)
        {
            context.Response.ContentType = "text/html";
            int id = int.Parse(context.Request["id"]);
            string strHtml = Commd.getFile("Dils.html");
            DataTable dt=getTable(id);
            strHtml = strHtml.Replace("{id}", dt.Rows[0]["id"].ToString());
            strHtml=strHtml.Replace("{name}",dt.Rows[0]["name"].ToString());
            strHtml=strHtml.Replace("{sex}",dt.Rows[0]["sex"].ToString());
            strHtml = strHtml.Replace("{c_id}", dt.Rows[0]["c_id"].ToString());
            context.Response.Write(strHtml);
        }
        DataTable getTable(int id)
        {
            string sql = string.Format("select id,name,sex,c_id from stus where id={0}",id);
            DataTable dt = SqlHelper.GetTable(sql);
            return dt;
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }

效果:
dCddr4ytDwAA&bo=VQVnAAAAAAABABA!&t=5&su=
當點了提交後,要在
EditPros.ashx進行處理

public class EditPros : IHttpHandler
    {
        public void Proce***equest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            int id=int.Parse(context.Request["id"]);
            string name = context.Request["name"];
            string sex = context.Request["sex"];
            int c_id = int.Parse(context.Request["c_id"]);
            if (onUp(id, name, sex, c_id))
            {
                context.Response.Redirect("List.ashx");
            }
        }
        bool onUp(int id, string name, string sex, int c_id)
        {
            string sql = string.Format("update stus set name='{0}',sex='{1}',c_id={2} where id={3}", name, sex, c_id, id);
            return SqlHelper.ExeNonQuery(sql,CommandType.Text,null);
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }

效果:
dOC1E4zdDwAA&bo=VQVgAAAAAAABABc!&t=5&su=
dLjaro*gDgAA&bo=MwLgAAAAAAABAPY!&t=5&su=
已經修改完成!
那麼要是添加的話,怎麼操作呢?
試試看。。。。。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章