博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
回味手写三层-增删改查
阅读量:5274 次
发布时间:2019-06-14

本文共 14318 字,大约阅读时间需要 47 分钟。

先看下全家福吧

切入正题

首先要有一个model,没有对象操作怎么行

using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace ClassModel{    public class ClassModels    {        private int cId;        public int CId        {            get { return cId; }            set { cId = value; }        }        private string cName;        public string CName        {            get { return cName; }            set { cName = value; }        }        private int cCount;        public int CCount        {            get { return cCount; }            set { cCount = value; }        }          }}

  

然后要有一个SqlHelper(不然操作数据库要累死了)

View Code
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Configuration; 6 using System.Data.SqlClient; 7 using System.Data; 8  9 namespace ClassDal10 {11     class SqlHelper12     {13         public static string connstr = ConfigurationManager.ConnectionStrings["sql"].ConnectionString;14         public static SqlDataReader ExcuteReader(string sql, params SqlParameter[] pams)15         {16             SqlConnection conn = new SqlConnection(connstr);17             using (SqlCommand cmd=new SqlCommand(sql,conn))18             {19                 if (pams!=null)20                 {21                     cmd.Parameters.AddRange(pams);22                 }23                 if (conn.State==System.Data.ConnectionState.Closed)24                 {25                     conn.Open();26                 }27                 return cmd.ExecuteReader();28             }29 30         }31 32         public static DataTable ExcuteDataTable(string sql,params SqlParameter[] pams)33         {34             using (SqlDataAdapter adapter=new SqlDataAdapter(sql,connstr))35             {36                 if (pams!=null)37                 {38                     adapter.SelectCommand.Parameters.AddRange(pams);39                 }40                 DataTable dt = new DataTable();41                 adapter.Fill(dt);42                 return dt;43             }44         }45         //增删改46         public static int ExcuteNonQuery(string sql, params SqlParameter[] pams)47         {48             using (SqlConnection conn=new SqlConnection(connstr))49             {50                 using (SqlCommand cmd=new SqlCommand(sql,conn))51                 {52                     if (pams!=null)53                     {54                         cmd.Parameters.AddRange(pams);55                     }56                     if (conn.State==ConnectionState.Closed)57                     {58                         conn.Open();59                     }60                     return cmd.ExecuteNonQuery();61                 }62             }63         }64 65         public static object ExcuteScalar(string sql, params SqlParameter[] pams)66         {67             using (SqlConnection conn=new SqlConnection(connstr))68             {69                 using (SqlCommand cmd=new SqlCommand(sql,conn))70                 {71                     if (pams!=null)72                     {73                         cmd.Parameters.AddRange(pams);74                     }75                     if (conn.State==ConnectionState.Closed)76                     {77                         conn.Open();78                     }79                     return cmd.ExecuteScalar();80                 }81             }82         }83     }84 85 86 }

然后写 数据访问层(DAL):

View Code
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Data; 6 using System.Data.SqlClient; 7 namespace ClassDal 8 { 9     public class ClassDals10     {11         //datetable 获取信息12         public DataTable GetAll()13         {14             string sql = "select *from Classes";15             return SqlHelper.ExcuteDataTable(sql);16         }17         // datereader 获取信息18         public SqlDataReader GetAllInfo()19         {20             string sql = "select *from Classes";21             return SqlHelper.ExcuteReader(sql);22         }23         public SqlDataReader GetInfoFromId(ClassModel.ClassModels model)24         {25             string sql = "select *from Classes where CID=@id";26             return SqlHelper.ExcuteReader(sql, new SqlParameter("@id",model.CId));27         }28         public int DeleteInfo(int id)29         {30             string sql = "delete from Classes where CID=@cid";31             SqlParameter pam = new SqlParameter("@cid",id);32             return SqlHelper.ExcuteNonQuery(sql,pam);33         }34         //CID, CName, CCount, CImage, CIsDel, CAddTime35         public int AddInfo(ClassModel.ClassModels model)36         {37             38             string sql = "insert into Classes(CName,CCount)values(@CName,@CCount)";39             SqlParameter[] pam = new SqlParameter[] {40             new SqlParameter("@CName",model.CName),41             new SqlParameter("@CCount",model.CCount)42             };43             return SqlHelper.ExcuteNonQuery(sql,pam);44         }45         public int UpdateInfo(ClassModel.ClassModels model)46         {47             //update Classes set CName='123',CCount='123' where CID='43'48             string sql = "update Classes set CName=@name,CCount=@count where CID=@id";49             SqlParameter[] pams = new SqlParameter[] {50             new SqlParameter("@id",model.CId),51             new SqlParameter("@name",model.CName),52             new SqlParameter("@count",model.CCount)53             };54             return SqlHelper.ExcuteNonQuery(sql,pams);55         }56        57     }58 }

在写 业务逻辑层(BLL):

View Code
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Data; 6 using ClassDal; 7 using System.Data.SqlClient; 8  9 namespace ClassBll10 {11     public class ClassBll12     {13         ClassDals dal = new ClassDals();14         public List
GetAll()15 {16 DataTable da = dal.GetAll();17 List
list = new List
();18 if (da.Rows.Count > 0)19 {20 ClassModel.ClassModels mode = null;21 foreach (DataRow row in da.Rows)22 {23 mode = new ClassModel.ClassModels();24 mode.CId = Convert.ToInt32(row["CID"].ToString());25 mode.CCount = Convert.ToInt32(row["CCount"].ToString());26 mode.CName = row["CName"].ToString();27 list.Add(mode);28 }29 return list;30 }31 else32 {33 return null;34 }35 }36 37 public List
GetAllInfo()38 {39 List
list = new List
();40 SqlDataReader reader = dal.GetAllInfo();41 while (reader.Read())42 {43 if (reader.HasRows)44 {45 ClassModel.ClassModels model = new ClassModel.ClassModels();46 model.CId = reader.GetInt32(0);47 model.CName = reader.GetString(1);48 model.CCount = reader.GetInt32(2);49 list.Add(model);50 51 }52 }53 return list;54 }55 public ClassModel.ClassModels GetInfoFromId(ClassModel.ClassModels model)56 {57 58 SqlDataReader reader = dal.GetInfoFromId(model);59 if (reader.Read())60 {61 if (reader.HasRows)62 {63 //ClassModel.ClassModels model = new ClassModel.ClassModels();64 model.CId = reader.GetInt32(0);65 model.CName = reader.GetString(1);66 model.CCount = reader.GetInt32(2);67 68 69 }70 }71 72 return model;73 }74 public int DeleteInfo(int id)75 {76 return dal.DeleteInfo(id);77 }78 public int AddInfo(ClassModel.ClassModels model)79 {80 return dal.AddInfo(model);81 }82 public int UpdateInfo(ClassModel.ClassModels model)83 {84 return dal.UpdateInfo(model);85 }86 87 }88 }

然后要写一个list页面显示数据,不然怎么增删改呢?(好像是废话!)

前台:

View Code
1 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="List.aspx.cs" Inherits="List" %> 2  3  4  5  6  7     学生成绩管理系统 8     21 22 23     
24
25
26
27
28
29 <%=GetAllInfo()%>30
编号 班级名称 人数 操作
31
32
33
34 35

后台:

View Code
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Web; 5 using System.Web.UI; 6 using System.Web.UI.WebControls; 7 using System.Text; 8  9 public partial class List : System.Web.UI.Page10 {11     protected void Page_Load(object sender, EventArgs e)12     {13 14     }15     public string GetAllInfo()16     {17         StringBuilder sb = new StringBuilder();18         ClassBll.ClassBll bll = new ClassBll.ClassBll();19         List
list = bll.GetAllInfo();20 foreach (ClassModel.ClassModels model in list)21 {22 sb.Append("");23 sb.Append("" + model.CId + "");24 sb.Append("" + model.CName + "");25 sb.Append("" + model.CCount + "");26 sb.Append("
修改");27 sb.Append("
删除");28 sb.Append("");29 }30 return sb.ToString();31 }32 }

然后先写增加 吧!要不然一会辛辛苦苦写的数据 都删完了!

这里完全可以把 增加 写到 list页面的,太懒了,回头改下

前台:

View Code
1 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="AddInfo.aspx.cs" Inherits="AddInfo" %> 2  3  4  5  6  7      8  9 10     
11
12 班级名称:
13 班级人数:
14
15
16
17
18 19

后台:

View Code
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Web; 5 using System.Web.UI; 6 using System.Web.UI.WebControls; 7  8 public partial class AddInfo : System.Web.UI.Page 9 {10     protected void Page_Load(object sender, EventArgs e)11     {12         string name = Request.Form["txtCName"];//txtCCount  isPostBack13         string countstr = Request.Form["txtCCount"];14         string ispostBack=Request.Form["isPostBack"];15         if (!string.IsNullOrEmpty(ispostBack))16         {17             int count = 0;18             if (int.TryParse(countstr,out count))19             {20                 ClassBll.ClassBll bll = new ClassBll.ClassBll();21                 ClassModel.ClassModels model = new ClassModel.ClassModels();22                 model.CName = name;23                 model.CCount = count;24                 if (bll.AddInfo(model)>0)25                 {26                     Response.Write("");27                 }28                 else29                 {30                     Response.Write("添加失败!");31                 }32 33             }34         }35     }36 }

该写删除了 一个一般处理程序搞定!

View Code
1 <%@ WebHandler Language="C#" Class="Delete" %> 2  3 using System; 4 using System.Web; 5  6 public class Delete : IHttpHandler { 7      8     public void ProcessRequest (HttpContext context) { 9         context.Response.ContentType = "text/html";10         string id=context.Request.QueryString["id"];11         if (!string.IsNullOrEmpty(id))12         {13             int sid = 0;14             if (int.TryParse(id,out sid))15             {16                 ClassBll.ClassBll bll = new ClassBll.ClassBll();17                 18                 if (bll.DeleteInfo(sid)>0)19                 {20                     context.Response.Write("");21                 }22                 else23                 {24                     context.Response.Write("删除失败!");25                 }26             }27         }28     }29  30     public bool IsReusable {31         get {32             return false;33         }34     }35 36 }

最后就是修改了,这个才是有点意思的

前台:

View Code
1 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Update.aspx.cs" Inherits="Update" %> 2  3  4  5  6      7  8  9     
10
11 班级名称:12 <%--用方法返回一个字符串--%>13 <%--
--%>14
15 班级人数:16
17
18
19
20
21 22

后台:

View Code
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Web; 5 using System.Web.UI; 6 using System.Web.UI.WebControls; 7  8 public partial class Update : System.Web.UI.Page 9 {10     ClassBll.ClassBll bll = new ClassBll.ClassBll();11     protected  ClassModel.ClassModels model = new ClassModel.ClassModels();12     protected void Page_Load(object sender, EventArgs e)13     {14         string isPostback = Request.Form["isPostBack"];15         //如果是准备提交保存16         if (!string.IsNullOrEmpty(isPostback))17         {18             int idCount = 0;19             if (int.TryParse(isPostback,out idCount))20             {21                 string cName = Request.Form["txtCName"];// txtCName txtCCount22                 string cCount = Request.Form["txtCCount"];23                 model.CId = idCount;24                 model.CName = cName;25                 model.CCount =Convert.ToInt32(cCount);26                 if (bll.UpdateInfo(model)>0)27                 {28                     Response.Write("");29                 }30                 else31                 {32                     Response.Write("修改失败!");33                 }34             }35         }36         else//如果是第一次访问37         {38             string id = Request.QueryString["id"];39 40             int idcount = 0;41             if (int.TryParse(id, out idcount))42             {43                 model.CId = idcount;44                 //查寻数据并存到model中45                 model = bll.GetInfoFromId(model);46             }47         }48 49 50 51     }52     //protected string CId()53     //{54     //    return model.CId.ToString();55     //}56     //protected string CCountInfo()57     //{58     //    return model.CCount.ToString();59     //}60     //protected string CCNameInfo()61     //{62     //    return model.CName;63     //}64 }

其实 修改 和 添加完全可以共用一个页面,或者一个div就行了,这里我就分开写了,看着简单点!

对了别忘了配置webconfig 哦!

View Code
1 
2
6
7
8
9
10
11
12
13

这样就大功搞成了,挺简单的吧! 

转载于:https://www.cnblogs.com/zhaozhengyan/archive/2012/04/09/add-select.html

你可能感兴趣的文章
第二次团队冲刺第二天
查看>>
bzoj 2257 (JSOI 2009) 瓶子与燃料
查看>>
11)Java abstract class 和 interface
查看>>
使用xrdp或Xmanager 远程连接 CentOS6
查看>>
Linux误删恢复
查看>>
Unity调用Windows窗口句柄,选择文件和目录
查看>>
HashMap循环遍历方式
查看>>
React Native 入门 调试项目
查看>>
C# 通过 Quartz .NET 实现 schedule job 的处理
查看>>
关于java之socket输入流输出流可否放在不同的线程里进行处理
查看>>
目前为止用过的最好的Json互转工具类ConvertJson
查看>>
Day13
查看>>
tensorflow saver简介+Demo with linear-model
查看>>
Luogu_4103 [HEOI2014]大工程
查看>>
Oracle——SQL基础
查看>>
项目置顶随笔
查看>>
Redis的安装与使用
查看>>
P1970 花匠
查看>>
java语言与java技术
查看>>
NOIP2016提高A组五校联考2总结
查看>>