关于增删查改的小总结

顾名思义:
·增-是添加的意思
·删-是删除的意思
·查-是查找的意思
·改-是修改的意思
*在学C#中,运用最多的就是增删查改了,可以说它在C#使用中无处不在
1、增:新增
在页面添加新的数据,并保存到数据库里面
一、新增·页面操作
①、打开新增的模态框
function abc(){
//清空表单
document.getElementById(“formClass”).resert();
//手动清空图片
$("#picture").attr(“src”,"")
//根据ID来判断新增还是修改
$("#xxID").val(0);
//修改头部标题
document.getElementById(“modalTitle”).innerHTML = “新增XX”;
//打开模态框
$("#productModal").modal(“show”);
}
②、点击保存
function abd(){
A1、获取填入模态框里面的数据(填入的数据=数据库表–>列)
var productId = $("#productID").val();//xxID(根据ID来判断新增还是修改)
var Name = document.getElementById(“Name”).value;//名称
var gender= document.getElementById(“gender”).value;//性别
var Code= document.getElementById(“Code”).value;//编号

A2、做数据验证(验证某些数据不能为空,并且不能等于undefined,并且编号必须为?位数)
if (Code == “” || Code == undefined || !/^\d{8}$/.test(Code)) {
layer.alert(“您忘记给编号了!或者请填写长度为8位数的编号!”);
return;
}

A3、判断接下来的操作是新增或修改
var strUrl = “”;
//判断当前的操作是新增还是修改
if (productId == “” || productId == undefined || productId<1)
{
//新增【strUrl = “@Url.Content(”~/域名/控制器名/模块名")";】
strUrl = “@Url.Content(”~/SystemSettings/Product/SaveInsert")";
}else {
//修改
strUrl = “@Url.Content(”~/SystemSettings/Product/saveUpdate")";
}
A4、实例FromData
var formData = new FormData();
formData.append(“productID”, xxId);//xxID
formData.append(“Name”, Name);//名称
formData.append(“gender”, gender);//性别
formData.append(“Code”, Code);//编号
A5、把获取的数据传到控制器,控制器把处理后的结果传回来
var xhr = new XMLHttpRequest();
xhr.open(“post”, strUrl)
xhr.onload = function () {
console.log(xhr.responseText)
var jsonData = JSON.parse(xhr.responseText);
if (jsonData.State) {
//刷新表格
tabSelectProduct();
//清空图片
$("#picture").attr(“src”, “”);
//关闭模态框
KaTeX parse error: Expected 'EOF', got '#' at position 3: ("#̲productModal").…"))
{
//判断新增的数据是否与数据库的数据重复
IntoldCount=myModel.S_Product.Count(o=>o.NameacProduct.Name||(o.CodeacProduct.Code ||o.gender == acProduct.gender));
if (oldCount == 0)
{
//新增数据
myModel.S_Product.Add(acProduct);
if (myModel.SaveChanges() > 0)
{
returnnJson.State = true;
returnnJson.Text = “新增成功!”;
}
else
{
returnnJson.Text = “新增失败,请重新操作!”;
}
}
Else
}
returnnJson.Text = “您添加的信息与当前的信息重复!”;
}
}
else
{
returnnJson.Text = “您忘记给编号了!或者请填写长度为8位数的编号!”;
}
#endregion
}
catch (Exception e)
{
Debug.WriteLine(e);
returnnJson.Text = “新增异常”;
}
return Json(returnnJson,JsonRequestBehavior.AllowGet);
}

2、删:删除
三、删除·页面操作
function delProduct(productID)
{
layer.confirm(“你确定要删除当前商品信息吗?”, { icon: 3, title: “提示” },
function (index) {
//关闭弹窗
layer.close(index);
//(异步请求)请求删除商品信息的方法
$.post("@Url.Content("~/SystemSettings/Product/Deleteproduct")",
{ productID: productID },
function (jsonData) {
layer.alert(jsonData.Text);
if (jsonData.State) {
//刷新表格
tabSelectProduct();
}
});
});
}
四、删除·控制器操作
public ActionResult Deleteproduct(int productID)
{
ReturnJson msg = new ReturnJson();
msg.State = false;
try
{
#region 删除商品信息的图片
//删除商品信息的图片
//==查询出旧的图片名称
var jdPicture = (from tabProduct in myModel.S_Product
where tabProduct.productID == productID
select tabProduct.pictureName).Single();
//查找文件是否存在
string deleteFilePath = Server.MapPath("~/Document/productPicture/") + jdPicture;
//判断之前是否存在图片,存在就先删除
if (System.IO.File.Exists(deleteFilePath))
{
//删除文件
System.IO.File.Delete(deleteFilePath);
}
#endregion

#region 删除商品信息数据(单条)
//查询要删除的数据(单条)
S_Product delProduct = myModel.S_Product.Single(o => o.productID == productID);
myModel.S_Product.Remove(delProduct);
if (myModel.SaveChanges() > 0)
{
msg.State = true;
msg.Text = “删除成功!!”;
}
else
{
msg.Text = “删除失败!”;
}
#endregion
}
catch (Exception e)
{
Debug.WriteLine(e);
msg.Text = “删除异常!!!”;
}
return Json(msg, JsonRequestBehavior.AllowGet);
}

五、删除·页面操作(多条删除)
function plDeletion() {
var checkStatus = layuiTable.checkStatus(“tabProduct”);//tabProduct 列表
//从列表中选中行数量 checkStatus.data选中数据 length 行
if (checkStatus.data.length > 0) {
var quantity = “”;
//循环获取选中的ID
for (var i = 0; i < checkStatus.data.length; i++) {
//“1;”“2;”“3;”
quantity += checkStatus.data[i].productID + ‘;’;
}
//去掉最后的";"
quantity = quantity.substring(0, quantity.length - 1);
layer.confirm(‘你确定要删除选中的’ + checkStatus.data.length + ‘条商品信息?’, { icon: 3, title: “提示” }, function (index) {
//异步请求
{ productIDs: quantity }, function (jsonData) {
if (jsonData.State == true) {
//关闭弹窗
layer.close(index);
//刷新表格
tabSelectProduct();
}
layer.alert(jsonData.Text, { icon: 6 });
});
});
}
else {
layer.alert(“请选择要删除的数据”, { icon: 0 });
}
}
六、删除·控制器操作(多条删除)
public ActionResult PlDeletion(string productIDs)
{
ReturnJson msg = new ReturnJson();
int intSuceessCount = 0;//纪录成功数
int intFailCount = 0;//记录失败数
if (!String.IsNullOrEmpty(productIDs))
{
//①字符串分隔
string[] ptudentIDs = productIDs.Split(’;’);
foreach (string strId in ptudentIDs)
{
try
{
//②获取商品ID
int productId = Convert.ToInt32(strId);
//③查询库存表中是否有数据(其它表)
int intCount = myModel.R_Repertory.Count(o => o.productID == productId);
if (intCount == 0)
{
//④查询要删除的数据
S_Product delProduct = myModel.S_Product.Single(o => o.productID == productId);
//判断是否有图片
if (!string.IsNullOrEmpty(delProduct.pictureName))
{
//获取路径
String deleteFilePath=Server.MapPath("~/Document/productPicture/") + delProduct.pictureName;
//判断之前是否存在图片,存在就先删除
if (System.IO.File.Exists(deleteFilePath))
{
//删除文件
System.IO.File.Delete(deleteFilePath);
}
}
//删除
//从商品表中删除数据
myModel.S_Product.Remove(delProduct);
//保存更改
myModel.SaveChanges();
//成功删除一条,就记录一条数据
intSuceessCount++;
}
else
{
msg.Text = “已发生业务的商品不能删除!”;
}
}
catch (Exception e)
{
intFailCount++;
Debug.WriteLine(e);
msg.Text = “删除异常”;
}
}
msg.State = true;
msg.Text = “总共删除” + ptudentIDs.Length + “条商品信息”;
if (intSuceessCount >0)
{
msg.Text += “,成功” + intSuceessCount + “条”;
}
if (intFailCount > 0)
{
msg.Text += “,失败” + intFailCount + “条”;
}
}
else
{
msg.Text = “请选择要删除的数据”;
}
return Json(msg, JsonRequestBehavior.AllowGet);
}

3、查:查询
七、查询·页面操作
function tabSelectProduct() {
//获取查询条件(下拉框条件查询)
var productID = document.getElementById(“productCategorysID”).value;//商品类型ID
var searchText = document.getElementById(“searchText”).value;//条件文本
var blDisable = $(’#blDisable’).prop(‘checked’);//显示禁用商品
var onGifts = $(’#onGifts’).prop(‘checked’);//显示禁用商品
var onBatching = $(’#onBatching’).prop(‘checked’);//显示禁用商品
//表格数据重载
tabProduct.reload({
url: “@Url.Content(”~/SystemSettings/Product/SelectProduct")",
where:{
productCategoryID: productID,
searchText: searchText,
blDisable: blDisable,
onGifts: onGifts,
onBatching: onBatching,
},
page: {
curr: 1//重新从第 1 页开始
}
});
}
八、查询·控制器操作
public ActionResult SelectProduct(LayuiTablePage layuiTablePage,int? productCategoryID, string searchText, bool blDisable, bool onGifts,bool onBatching)
{
//查询数据库中商品表的所有数据(多表查询)
var specialty = (from tbProduct in myModel.S_Product
join tbProductCategory in myModel.S__ProductCategory on tbProduct.productCategoryID
equals tbProductCategory.productCategoryID
join tbCommoditiesUnit in myModel.S__CommoditiesUnit on tbProduct.commoditiesUnitID
equals tbCommoditiesUnit.commoditiesUnitID
select new ProductVo
{
//查询内容(格式:商品ID=商品表中的商品ID)
productID = tbProduct.productID,//商品ID
productCategoryID = tbProductCategory.productCategoryID,//类别ID
commoditiesUnitID = tbCommoditiesUnit.commoditiesUnitID,//单位ID
productCode = tbProduct.productCode,//编号
productName = tbProduct.productName,//名称
specifications = tbProduct.specifications,//规格型号
noGifts = tbProduct.noGifts,//赠品
disabledNo = tbProduct.disabledNo,//禁用
purchasePrice = tbProduct.purchasePrice,//预设进价
commodityBarcodes = tbProduct.commodityBarcodes,//商品条码
color = tbProduct.color,//颜色
averagePrice = tbProduct.averagePrice,//商品均价
totalCost = tbProduct.totalCost,//成本总额
sellingPrice = tbProduct.sellingPrice,//预设售价
firstPrice = tbProduct.firstPrice,//一级进价
secondPrice = tbProduct.secondPrice,//二级进价
thirdPrice = tbProduct.thirdPrice,//三级进价
fourthPrice = tbProduct.fourthPrice,//四级进价
fifthPrice = tbProduct.fifthPrice,//五级进价
sixprice = tbProduct.sixprice,//六级进价
manufacturer = tbProduct.manufacturer,//生产厂商
remark = tbProduct.remark,//备注
pictureName = tbProduct.pictureName,//图片
batching = tbProduct.batching,//配料
productCategory = tbProductCategory.productCategory,//商品类别名称
commoditiesUnit = tbCommoditiesUnit.commoditiesUnit,//商品单位名称
});
//条件筛选
if (productCategoryID != null&& productCategoryID > 0)
{
specialty = specialty.Where(o => o.productCategoryID == productCategoryID);
}
//商品信息
if (!string.IsNullOrEmpty(searchText))
{
searchText = searchText.Trim();//去空格
specialty = specialty.Where(o => o.productName.Contains(searchText) ||
o.productCode.Contains(searchText) ||
o.color.Contains(searchText)||
o.commoditiesUnit.Contains(searchText) ||
o.commodityBarcodes.Contains(searchText));
}
//禁用否
if (blDisable == true)
{
specialty = specialty.Where(o => o.disabledNo == blDisable);
}
//赠送否
if (onGifts == true)
{
specialty = specialty.Where(o => o.noGifts == onGifts);
}
//配料组成
if (onBatching == true)
{
specialty = specialty.Where(o => o.batching == onBatching);
}
//统计所有数据的条数
int totalRow = specialty.Count();
//提取当前页的数据
List listpecialty = specialty
//.OrderByDescending(o => o.productCode)
.OrderBy(o=> o.productCode)
.Skip(layuiTablePage.GetStartIndex())
.Take(layuiTablePage.limit)
.ToList();
//构建返回值
LayuiTableData layuiTableData = new LayuiTableData
{
count = totalRow,
data = listpecialty
};
return Json(layuiTableData,JsonRequestBehavior.AllowGet);
}

4、改:修改
九、修改·页面操作
function openUpdateModal(productID) {
//alert(“暂时不能修改”);
//return;
//重置表单
//document.getElementById(“formClass”).reset();
$("#formClass").get(0).reset();
//修改头部标题
document.getElementById(“modalTitle”).innerHTML = “修改商品”;
//根据ID查询商品信息(数据回填&异步请求)
$.post("@Url.Content("~/SystemSettings/Product/SaveproductByID")", { productId: productID }, function (rtMsg) {
//回填表单数据
loadDatatoForm(“formClass”, rtMsg);
//图片路径(文件夹)
if (rtMsg.pictureName == null || rtMsg.pictureName == “” || rtMsg.pictureName == undefined) {
$("#picture").attr(“src”, “”);
}
var pictureUrl = ‘@Url.Content("~/Document/productPicture/")’ + rtMsg.pictureName;
$("#picture").attr(“src”, pictureUrl);
}
})
//打开模态框
$("#productModal").modal(“show”);
}

十、修改·控制器操作
A1数据回填
public ActionResult SaveproductByID(int productId)
{
try
{
S_Product saveproduct = myModel.S_Product.Single(o=>o.productID == productId);
return Json(saveproduct, JsonRequestBehavior.AllowGet);
}
catch (Exception e)
{
Debug.WriteLine(e);
return Json(null,JsonRequestBehavior.AllowGet);
}
}

A2修改操作
public ActionResult saveUpdate (S_Product adProduct, HttpPostedFileBase bytePicture)
{
ReturnJson returnnJson = new ReturnJson();
try
{
#region 修改图片
//修改图片
//==查询出旧的图片名称
var jdPicture = (from tabProduct in myModel.S_Product
where tabProduct.productID == adProduct.productID
select tabProduct.pictureName).Single();
//判断图片是否上传
if (bytePicture != null && bytePicture.ContentLength > 0)
{
//=检查存放图片的目录是否存在
if (!System.IO.Directory.Exists(Server.MapPath("~/Document/productPicture/")))
{
System.IO.Directory.CreateDirectory(Server.MapPath("~/Document/productPicture/"));
}
//保存图片
//获取文件扩展名
string imgExtension = System.IO.Path.GetExtension(bytePicture.FileName);
//拼接要保存的文件名称
string fileName = DateTime.Now.ToString(“yyyMMddHHmmssffff”) + “_” + Guid.NewGuid() + imgExtension;
//拼接文件保存的路径
string filePath = Server.MapPath("~/Document/productPicture/") + fileName;
//保存上传的文件到硬盘
bytePicture.SaveAs(filePath);
//保存文件名称到数据库
adProduct.pictureName = fileName;
//替换图片(把旧的图片删除,把新的添加上去)
//查找文件是否存在
string deleteFilePath = Server.MapPath("~/Document/productPicture/") + jdPicture;
//判断之前是否存在图片,存在就先删除
if (System.IO.File.Exists(deleteFilePath))
{
//删除文件
System.IO.File.Delete(deleteFilePath);
}
}
else
{
//未上传
adProduct.pictureName = jdPicture;
}
#endregion

#region 做修改的数据验证
//做修改的数据验证
if (adProduct.productCategoryID > 0)
{
if (adProduct.commoditiesUnitID > 0)
{
if (!string.IsNullOrEmpty(adProduct.productName))
{
if (!string.IsNullOrEmpty(adProduct.productCode) && Regex.IsMatch(adProduct.productCode, “^\d{8}KaTeX parse error: Expected '}', got '&' at position 62: …odityBarcodes) &̲& Regex.IsMatch…”))
{
//判断是否重复(除自身外)
int oldCount = myModel.S_Product.Count(o => o.productName == adProduct.productName &&
o.productID != adProduct.productID &&
(o.productCode == adProduct.productCode ||
o.commodityBarcodes == adProduct.commodityBarcodes));
if (oldCount == 0)
{
//修改数据
myModel.Entry(adProduct).State = System.Data.Entity.EntityState.Modified;
if (myModel.SaveChanges() > 0)
{
returnnJson.State = true;
returnnJson.Text = “修改成功!”;
}
else
{
returnnJson.Text = “修改失败,请重新操作!”;
}
}
else
{
returnnJson.Text = “您添加的商品信息与当前的商品信息重复!”;
}
}
else
{
returnnJson.Text = “请填写长度为11位数的商品条码!”;
}
}
else
{
returnnJson.Text = “请填写长度为8位数的商品编号!”;
}
}
else
{
returnnJson.Text = “您忘记给商品名称了!”;
}
}
else
{
returnnJson.Text = “您忘记选择商品单位了!”;
}
}
else
{
returnnJson.Text = “您忘记选择商品类别了!”;
}
#endregion
}
catch (Exception e)
{
Debug.WriteLine(e);
returnnJson.Text = “修改异常”;
}
return Json(returnnJson, JsonRequestBehavior.AllowGet);
}
以上是我对增-删-查-改 的小总结,希望对你们有帮助

以上就是我的分享,请多多指教。如果有更好的方法或不懂得地方欢迎在评论区教导和提问

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值