一般處理程序對數據庫的怎刪改查操作


先建立一個一般處理程序,ListHandler.ashx,然后將數據庫中的數據讀取出來,並在網頁中顯示 代碼如下:

<%@ WebHandler Language="C#" Class="ListHandler" %>

using System;
using System.Web;
using System.Configuration;
using System.Data.SqlClient;
using System.Text;

public class ListHandler : IHttpHandler {

    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "text/html";
        //context.Response.Write("Hello World");

        StringBuilder sb = new StringBuilder();//拼接字符串
        sb.Append("<html><head></head><body><a href='addDate.html'>增加站點信息</a>");//APPend()要成對出現
                                               //下面拼接表頭
        sb.Append("<table><tr><th>Id</th>&nbsp;<th>站名</th>&nbsp;<th>站號</th>&nbsp;<th>登陸用戶名</th>&nbsp;<th>登陸密碼</th><th>操&nbsp;&nbsp;&nbsp;&nbsp;作</th></tr>");

        string str= ConfigurationManager.ConnectionStrings["BjQx"].ConnectionString;
        using (SqlConnection conn=new SqlConnection (str))
        {
            string sql = "select * from Tbl_ZhanMing";
            using (SqlCommand cmd=new SqlCommand (sql,conn))
            {
                conn.Open();
                using (var reader=cmd.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        //拼接字符串
                        sb.AppendFormat("<tr><td>{0}</td><td>{1}</td><td>{2}</td><td>{3}</td><td>{4}</td>"+
                            "<td><a href='DetailHandler.ashx?Id={0}' target=_blank>詳情</a>&nbsp;&nbsp;&nbsp;&nbsp;"+
                            "<a onclick='return confirm(\"是否刪除?\")'  href='Delete.ashx?Id={0}' >刪除</a> "+
                            "&nbsp;&nbsp;&nbsp;&nbsp;<a onclick='return confirm(\"是否修改\")'  href='EditShow.ashx?Id={0}&action=show'>修改</a></td></tr>",
                            reader.GetInt32(0), reader["站名"], reader["站號"], reader["登陸用戶名"], reader["登陸密碼"]);
                    }
                }
            }

        }
        sb.Append("</table>");
        sb.Append("</body></html>");
        //把上面拼接的字符串寫入網頁中
        context.Response.Write(sb.ToString());//一般要寫為sb.ToString()
    }

    public bool IsReusable {
        get {
            return false;
        }
    }

}

 

 

點擊 “詳情”時,則跳轉到'DetailHandler.ashx頁面,該頁面顯示出所點擊的站點信息,代碼如下:

<%@ WebHandler Language="C#" Class="DetailHandler" %>

using System;
using System.Web;
using System.Configuration;
using System.Data.SqlClient;
using System.Text;
using System.Data;
using System.IO;

public class DetailHandler : IHttpHandler {

    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "text/html";
        //context.Response.Write("Hello World");
        StringBuilder sb = new StringBuilder();


        //先接收點擊“詳情”發過來的信息
        string Id = context.Request.QueryString["Id"];
        int ZId = int.Parse(Id);



        //通過ID號,連接數據庫並將內容顯示在該網頁中  用SQLDataAdapter
        string strLink = ConfigurationManager.ConnectionStrings["BjQx"].ConnectionString;
        string sql = "select * from Tbl_ZhanMing where Id=@Id";
        using (SqlDataAdapter adapter = new SqlDataAdapter(sql, strLink))
        {
            //傳遞參數過來
            adapter.SelectCommand.Parameters.Add("@Id", ZId);
            
              

            //創建一個表格對象
            DataTable dt = new DataTable();
            adapter.Fill(dt);//在網頁中填充表格
                             //下面進行填充表格
            sb.AppendFormat("<tr><td>Id:</td><td>{0}</td></tr>", dt.Rows[0]["Id"]);
            sb.AppendFormat("<tr><td>站名:</td><td>{0}</td></tr>", dt.Rows[0]["站名"]);
            sb.AppendFormat("<tr><td>站號:</td><td>{0}</td></tr>", dt.Rows[0]["站號"]);
            sb.AppendFormat("<tr><td>登陸用戶名:</td><td>{0}</td></tr>", dt.Rows[0]["登陸用戶名"]);
            sb.AppendFormat("<tr><td>登陸密碼:</td><td>{0}</td></tr>", dt.Rows[0]["登陸密碼"]);
        }
        //寫一個HTML模板
        string path = context.Request.MapPath("/showresult.html");
        string texttemp = File.ReadAllText(path);//將整個html網頁賦值給他
        string result = texttemp.Replace("@NBBiJie", sb.ToString());
        context.Response.Write(result);



    }

    public bool IsReusable {
        get {
            return false;
        }
    }

}

 

 當點擊“增加站點信息”按鈕時,則跳轉到addDate.html 頁面,在該HTML表單里寫入<form id="frmAdd" action="AddDateHandle.ashx">,提交表單時則跳轉到

AddDateHandle.ashx頁。

addDate.html 頁面代碼如下:

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
    <meta charset="utf-8" />
</head>
<body>
    <h1>請增加如下內容:</h1>
<form id="frmAdd" action="AddDateHandle.ashx">
    <table>
        <tr>
            <td>站名:</td>
            <td>
                <input type="text" name="zhanming" />
            </td>
        </tr>
        <tr>
            <td>站號:</td>
            <td>
                <input type="text" name="zhanhao" />
            </td>
        </tr>
        <tr>
            <td>登陸用戶名:</td>
            <td>
                <input  type="text" name="username"/>
            </td>
        </tr>
        <tr>
            <td>登錄密碼:</td>
            <td>
                <input type="text" name="password" />
            </td>
        </tr>
        <tr>
            <td>
                &nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;<input type="submit" value="提交" />
            </td>
            <td>
                &nbsp;&nbsp; &nbsp;&nbsp;<input type="reset" value="重置" />
            </td>
        </tr>
    </table>
</form>
</body>
</html>

AddDateHandle.ashx一般處理程序頁面代碼如下:

<%@ WebHandler Language="C#" Class="AddDateHandle" %>

using System;
using System.Web;
using System.Configuration;
using System.Data.SqlClient;

public class AddDateHandle : IHttpHandler {

    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "text/html";
        //context.Response.Write("Hello World");
        //拿到addDate.html上交來的數據
        string zhanming = context.Request["zhanming"];
        int zhanhao =int.Parse(context.Request["zhanhao"]);
        string username = context.Request["username"];
        string passsword = context.Request["password"];

        //接下來做數據庫插入操作
        string str = ConfigurationManager.ConnectionStrings["BJQx"].ConnectionString;
        using (SqlConnection conn=new SqlConnection (str))
        {
            string sql = string.Format("insert into Tbl_ZhanMing (站名,站號,登陸用戶名,登陸密碼) values ('{0}',{1},'{2}','{3}') select * from Tbl_ZhanMing",zhanming,zhanhao,username,passsword);
           
            using (SqlCommand cmd=new SqlCommand (sql,conn))
            {
                conn.Open();
                int r= cmd.ExecuteNonQuery();

            }

        }

        context.Response.Redirect("ListHandler.ashx");
    }

    public bool IsReusable {
        get {
            return false;
        }
    }

}

以上代碼完成了對數據的增加,全部顯示,和顯示所點擊那一條信息的詳情的操作。

 當在ListHandler.ashx所顯示的頁面上,點擊“刪除”按鈕時,則跳轉到Delete.ashx頁。此步驟完成對數據庫表中的數據進行刪除操作。該頁面的代碼如下:

 

<%@ WebHandler Language="C#" Class="Delete" %>

using System;
using System.Web;
using System.Configuration;
using System.Data.SqlClient;

public class Delete : IHttpHandler {

    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "text/plain";
        //context.Response.Write("Hello World");
        //獲取提交刪除的Id
        string Id= context.Request["Id"];
        int delId = int.Parse(Id);

        //連接數據庫進行刪除操作
        string constr = ConfigurationManager.ConnectionStrings["BJQx"].ConnectionString;
        using (SqlConnection conn=new SqlConnection (constr))
        {
            string sql = "delete from Tbl_ZhanMing where Id=@Id";
            using (SqlCommand cmd=new SqlCommand (sql,conn))
            {
                conn.Open();
                cmd.Parameters.Add(new SqlParameter("@Id", delId));
                int rows = cmd.ExecuteNonQuery();
                if (rows>0)
                {
                    //刪除成功
                    context.Response.Redirect("ListHandler.ashx");
                }
                else
                {
                        context.Response.Write("刪除失敗!");
                }
            }
        }
    }

    public bool IsReusable {
        get {
            return false;
        }
    }

}

 

一下代碼對數據庫列表進行修改操作,當點擊“修改”按鈕時,則跳轉到EditShow.ashx,代碼如下:

 

<%@ WebHandler Language="C#" Class="Alter" %>

using System;
using System.Web;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
using System.IO;

public class Alter : IHttpHandler {

    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "text/html";//   切記 此處要改為html,否則就把源碼輸出來了!
        //用於顯示修改數據的

        if (context.Request["action"] == "show")
        {

            //先拿到需要修改的那一行的Id
            int altId = int.Parse(context.Request["Id"]);
            //建立數據庫連接 填充網頁一般用SqlDataAdapter

            string str = ConfigurationManager.ConnectionStrings["BjQx"].ConnectionString;
            string sql = "select *from Tbl_ZhanMing where Id=@Id";
            using (SqlDataAdapter adapter = new SqlDataAdapter(sql, str))
            {
                //將ID傳遞過來
                adapter.SelectCommand.Parameters.Add("@Id", altId);
                //填充表格
                DataTable dt = new DataTable();//創建一個表格對象
                adapter.Fill(dt);
                //直接在后台拼接字符串太麻煩,所以寫一個模板 EditTemp.html
                string strResult = File.ReadAllText(context.Request.MapPath("EditTemp.html"));
                //File.ReadAllText()需要的是一個絕對路徑
                strResult = strResult.Replace("@txtZhanMing", dt.Rows[0]["站名"].ToString());//第一行站名這一列全部顯示出來
                strResult = strResult.Replace("@txtZhanHao", dt.Rows[0]["站號"].ToString());
                strResult = strResult.Replace("@txtUserName", dt.Rows[0]["登陸用戶名"].ToString());
                strResult = strResult.Replace("@txtPassWord", dt.Rows[0]["登陸密碼"].ToString());
                    strResult = strResult.Replace("@Id", dt.Rows[0]["Id"].ToString());
                    
                context.Response.Write(strResult);
            }
        }
    }

    public bool IsReusable {
        get {
            return false;
        }
    }

}

 

EditShow.ashx需要一個html模板EditTemp.html,代碼如下:

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
    <meta charset="utf-8" />
</head>
<body>
    <form method="post" action="EditProcess.ashx">
        <input type="hidden" name="hidId" value="@Id" />
        <table>
            <tr>
                <td>站名:</td>
                <td>
                    <input type="text" name="txtZhanMing" value="@txtZhanMing"/>
                </td>
            </tr>
            <tr>
                <td>站號:</td>
                <td>
                    <input type="text" name="txtZhanHao" value="@txtZhanHao" />
                </td>
            </tr>
            <tr>
                <td>登陸用戶名:</td>
                <td>
                    <input type="text" name="txtUserName" value="@txtUserName"/>
                </td>
            </tr>
            <tr>
                <td>登錄密碼:</td>
                <td>
                    <input type="text" name="txtPassWord" value="@txtPassWord" />
                </td>
            </tr>
            <tr>
                <td colspan="2">
                    <input type="submit" value="修改" />
                </td>
            </tr>

        </table>

    </form>
</body>
</html>

 

EditTemp.html頁面上,當點擊“修改”按鈕時,跳轉到EditProcess.ashx,則可以直接對所選中的數據庫列表進行修改操作。代碼如下:

 

<%@ WebHandler Language="C#" Class="EditProcess" %>

using System;
using System.Web;
using System.Configuration;
using System.Data.SqlClient;

public class EditProcess : IHttpHandler {

    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "text/html";
        //用於修改數據的
        //先拿到要修改的這一行的信息,不知道Id,因此只能單獨取,我們知道name的值
        string txtZhanMing = context.Request["txtZhanMing"];
        int txtZhanHao = int.Parse(context.Request["txtZhanHao"]);
        string txtUserName = context.Request["txtUserName"];
        string txtPassWord = context.Request["txtPassWord"];
        int editId = int.Parse(context.Request["hidId"]);//通過網頁的名字來取ID
        //建立數據庫連接
        string str = ConfigurationManager.ConnectionStrings["BjQx"].ConnectionString;
        using (SqlConnection conn=new SqlConnection (str))
        {
            string sql = "update Tbl_ZhanMing set 站名=@txtZhanMing,站號=@txtZhanHao,登陸用戶名=@txtUserName,登陸密碼=@txtPassWord where Id=@Id";
            using (SqlCommand cmd=new SqlCommand(sql,conn))
            {
                //將sql語句的參數全部給其賦值
                cmd.Parameters.Add(new SqlParameter("@Id", editId));
                cmd.Parameters.Add(new SqlParameter("@txtZhanMing", txtZhanMing));
                cmd.Parameters.Add(new SqlParameter("@txtZhanHao", txtZhanHao));
                cmd.Parameters.Add(new SqlParameter("@txtUserName", txtUserName));
                cmd.Parameters.Add(new SqlParameter("@txtPassWord", txtPassWord));
                conn.Open();
                int r = cmd.ExecuteNonQuery();
                if (r>0)
                {
                    context.Response.Redirect("ListHandler.ashx");
                }
                else
                {
                    context.Response.Write("修改失敗!");
                }
            }
        }
    }

    public bool IsReusable {
        get {
            return false;
        }
    }

}

 

以上代碼實現了對數據庫的增刪改查操作。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM