作为一名开发人员,我们经常需要对数据库中的数据进行增删改查(CRUD)操作。在本篇博客中,我们将重点介绍Lauiyi这个优秀的库是如何帮助我们简化和优化这些操作的。
Lauiyi是一个强大的开源工具,提供了丰富的函数和方法,可以轻松地实现对数据库的增删改查操作。下面让我们逐一介绍一下这些功能。
增加(Create)
在Lauiyi中,增加数据非常简单。我们只需使用add()或insert()函数,指定要添加的数据和目标表名,即可将数据插入到数据库中。例如:
python
from lauiyi import Lauiyi
创建Lauiyi对象
1.后台准备
1.dao方法
package com.zking.dao; import java.util.List; import java.util.Map; import com.zking.entity.User; import com.zking.util.BaseDao; import com.zking.util.PageBean; import com.zking.util.StringUtils; public class UserDao extends BaseDao<User> { public List<User> executeQuery(Class<User> clz, PageBean pageBean) throws Exception { String sql="select * from t_oa_user where 1=1 "; return super.executeQuery(sql, User.class, pageBean); } public User login(User user) throws Exception { String sql="select * from t_oa_user where loginName ='"+user.getLoginName()+"' and pwd = '"+user.getPwd()+"'"; List<User> list = super.executeQuery(sql, User.class, null); if (list!=null&&list.size()==1) { return list.get(0); } return null; } public int registered(User user) throws Exception { String sql = "insert into t_oa_user(name,loginName,pwd,rid) values(?,?,?,?)"; return executeUpdate(sql, user,new String[] {"name","loginName","pwd","rid"}); } public List<Map<String, Object>> userRole(User user, PageBean pageBean) throws Exception { String sql="SELECT\r\n" + " u.*,\r\n" + " (\r\n" + "CASE\r\n" + " \r\n" + " WHEN u.rid = '1' THEN\r\n" + " '管理员' \r\n" + " WHEN u.rid = '2' THEN\r\n" + " '发起者' \r\n" + " WHEN u.rid = '3' THEN\r\n" + " '审批者' \r\n" + " WHEN u.rid = '4' THEN\r\n" + " '参与者' \r\n" + " WHEN u.rid = '5' THEN\r\n" + " '会议管理员' ELSE '其它' \r\n" + "END \r\n" + " ) rname \r\n" + "FROM\r\n" + " `t_oa_user` u where 1=1 "; String name=user.getName(); if (StringUtils.isNotBlank(name)) { sql+=" and name like '%"+name+"%'"; } return super.executeQuery(sql, pageBean); } public int add(User user) throws Exception { String sql="insert into t_oa_user(name,loginName,pwd) values(?,?,?)"; return super.executeUpdate(sql, user, new String[]{"name","loginName","pwd"}); } public int del(User user) throws Exception { String sql="delete from where id = ?"; return super.executeUpdate(sql, user, new String[]{"id"}); } public int edit(User user) throws Exception { String sql="update t_oa_user set name = ?,loginName=?,pwd=? where id=?"; return super.executeUpdate(sql, user, new String[]{"name","loginName","pwd" ,"id"}); } public static void main(String[] args) throws Exception { User user = new User(); // user.setLoginName("ll"); user.setName("朱"); // user.setPwd("789"); // int add = new UserDao().add(user); // List<Map<String, Object>> userRole = new UserDao().userRole(user, null); System.out.println(userRole); } }
2.子实现类
package com.zking.web; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.zking.dao.UserDao; import com.zking.entity.User; import com.zking.framework.ActionSupport; import com.zking.framework.ModelDriver; import com.zking.util.PageBean; import com.zking.util.R; import com.zking.util.ResponseUtil; public class Useraction extends ActionSupport implements ModelDriver<User> { private User user=new User(); private UserDao userdao=new UserDao(); public void login(HttpServletRequest req, HttpServletResponse resp) { try { User u = userdao.login(user); ResponseUtil.writeJson(resp, u); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void registered(HttpServletRequest req, HttpServletResponse resp) { try { int n = userdao.registered(user); if(n>0) { ResponseUtil.writeJson(resp, n); } ResponseUtil.writeJson(resp, null); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void userRole(HttpServletRequest req, HttpServletResponse resp) { try { PageBean pagebean=new PageBean(); pagebean.setRequest(req); List<Map<String, Object>> userRole = userdao.userRole(user, pagebean); Map<String, Object>map=new HashMap<String, Object>(); ResponseUtil.writeJson(resp, R.ok(0, "查询成功", pagebean.getTotal(),userRole) ); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void add(HttpServletRequest req, HttpServletResponse resp) throws Exception { int add = userdao.add(user); ResponseUtil.writeJson(resp, R.ok(0, "新增成功") ); } public void del(HttpServletRequest req, HttpServletResponse resp) throws Exception { int del = userdao.del(user); ResponseUtil.writeJson(resp, R.ok(0, "删除成功") ); } public void edit(HttpServletRequest req, HttpServletResponse resp) throws Exception { int edit = userdao.edit(user); ResponseUtil.writeJson(resp, R.ok(0, "修改成功") ); } @Override public User getModel() { // TODO Auto-generated method stub return user; } }
2.R工具类的使用
package com.zking.util; import java.util.HashMap; public class R extends HashMap{ public R data(String key, Object value) { this.put(key, value); return this; } public static R ok(int code, String msg) { R r = new R(); r.data("success", true).data("code", code).data("msg", msg); return r; } public static R error(int code, String msg) { R r = new R(); r.data("success", false).data("code", code).data("msg", msg); return r; } public static R ok(int code, String msg,Object data) { R r = new R(); r.data("success", true).data("code", code).data("msg", msg).data("data", data); return r; } public static R ok(int code, String msg, long count, Object data) { R r = new R(); r.data("success", true).data("code", code).data("msg", msg).data("count", count).data("data", data); return r; } }
3.查询前端代码实现
前端页面
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ include file = "common/header.jsp" %> <!DOCTYPE html > <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <style type="text/css"> .layui-show{ height:100%; } .layui-tab, .layui-tab-content{ height:100%; } </style> <div class="layui-layout layui-layout-admin"> <div class="layui-header"> <div class="layui-logo layui-hide-xs layui-bg-black">layout demo</div> <!-- 头部区域(可配合layui 已 有的水平导航) --> <ul class="layui-nav layui-layout-left"> </ul> <!-- 个人头像及账号操作 --> <ul class="layui-nav layui-layout-right"> <li class="layui-nav-item layui-hide layui-show-md-inline-block"> <a href="javascript:;"> <img src="//tva1.sinaimg.cn/crop.0.0.118.118.180/5db11ff4gw1e77d3nqrv8j203b03cweg.jpg" class="layui-nav-img"> tester </a> <dl class="layui-nav-child"> <dd><a href="">Your Profile</a></dd> <dd><a href="">Settings</a></dd> <dd><a href="login.jsp">Sign out</a></dd> </dl> </li> <li class="layui-nav-item" lay-header-event="menuRight" lay-unselect> <a href="javascript:;"> <i class="layui-icon layui-icon-more-vertical"></i> </a> </li> </ul> </div> <div class="layui-side layui-bg-black"> <div class="layui-side-scroll"> <!-- 左侧导航区域(可配合layui已有的垂直导航) --> <ul id="menu" class="layui-nav layui-nav-tree" lay-filter="menu"> </ul> </div> </div> <div class="layui-body"> <!-- 内容主体区域 --> <div style="padding: 15px;"> <div class="layui-tab" lay-filter="demo" lay-allowclose="true"> <ul class="layui-tab-title"> <li class="layui-this" lay-id="11">网站设置</li> <li lay-id="22">用户管理</li> <li lay-id="33">权限分配</li> <li lay-id="44">商品管理</li> <li lay-id="55">订单管理</li> </ul> <div class="layui-tab-content" style=" height:600px" > <div class="layui-tab-item layui-show">内容1</div> <div class="layui-tab-item">内容2</div> <div class="layui-tab-item">内容3</div> <div class="layui-tab-item">内容4</div> <div class="layui-tab-item">内容5</div> </div> </div> </div> </div> <div class="layui-footer"> <!-- 底部固定区域 --> 底部固定区域 </div> </div> <script src="static/index.js" > </script> </body> </html>
4.增删改实现
1.弹出层
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>博客的编辑界面</title> </head> <body> <form action="${pageContext.request.contextPath }/blog.action?methodName=${empty b ? 'add' : 'edit'}" method="post"> id:<input type="text" name="id" value="${b.id }"><br> title:<input type="text" name="title" value="${b.title }"><br> keyWord:<input type="text" name="keyWord" value="${b.keyWord }"><br> <input type="submit"> </form> </body> </html>
2.浮层
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@include file="/common/header.jsp" %> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <%-- <script type="text/javascript" src="${pageContext.request.contextPath }/static/js/system/userEdit.js"></script> --%><title>用户新增</title> </head> <style> .layui-form-select dl{ max-height:150px; } </style> <body> <div style="padding:10px;"> <form class="layui-form layui-form-pane" lay-filter="user"> <input type="hidden" name="id"/> <div class="layui-form-item"> <label class="layui-form-label">用户名称</label> <div class="layui-input-block"> <input type="text" id="name" name="name" autocomplete="off" placeholder="请输入用户名" class="layui-input"> </div> </div> <div class="layui-form-item"> <label class="layui-form-label">用户角色</label> <div class="layui-input-block"> <select name="rid"> <option value="">---请选择---</option> <option value="1">管理员</option> <option value="2">发起者</option> <option value="3">审批者</option> <option value="4">参与者</option> <option value="5">会议管理员</option> </select> </div> </div> <div class="layui-form-item"> <label class="layui-form-label">登录账号</label> <div class="layui-input-block"> <input type="text" name="loginName" lay-verify="required" placeholder="请输入账号" autocomplete="off" class="layui-input"> </div> </div> <div class="layui-form-item"> <label class="layui-form-label">登录密码</label> <div class="layui-input-block"> <input type="password" name="pwd" placeholder="请输入密码" autocomplete="off" class="layui-input"> </div> </div> </form> </div> </body> </html>
3分离的js代码
1.userManage.js
var table,$; var row; layui.use(['table','jquery','layer'], function(){ table = layui.table layer=layui.layer ,$=layui.jquery; initTable(); $("#btn_search").click( function(){ query(); }); $("#btn_add").click( function(){ row=null; edit('新增'); } ); }); function edit(title){ layer.open({ type: 2, //layer提供了5种层类型。可传入的值有:0(信息框,默认)1(页面层)2(iframe层)3(加载层)4(tips层) title:title, area: ['660px', '340px'], //宽高 skin: 'layui-layer-rim', //样式类名 content: 'jsp/system/userEdit.jsp', //书本编辑页面 btn:['保存','关闭'], yes: function(index, layero){ //调用子页面中提供的getData方法,快速获取子页面的form表单数据 let data= $(layero).find("iframe")[0].contentWindow.getData(); console.log(data); //判断title标题 let methodName="add"; if(title=="编辑") methodName="edit"; $.post('user.action?methodName='+methodName, data,function(rs){ if(rs.success){ //关闭对话框 layer.closeAll(); //调用查询方法刷新数据 query(); }else{ layer.msg(rs.msg,function(){}); } },'json'); }, btn2: function(index, layero){ layer.closeAll(); } }); } function query(){ table.reload('test', { where: { //设定异步数据接口的额外参数,任意设 name: $("#name").val() } ,page: { curr: 1 //重新从第 1 页开始 } }); //只重载数 }; function initTable(){ table.render({ elem: '#test' ,url:'user.action?methodName=userRole' ,toolbar: '#toolbarDemo' //开启头部工具栏,并为其绑定左侧模板 ,defaultToolbar: ['filter', 'exports', 'print', { //自定义头部工具栏右侧图标。如无需自定义,去除该参数即可 title: '提示' ,layEvent: 'LAYTABLE_TIPS' ,icon: 'layui-icon-tips' }] ,title: '用户数据表' ,cols: [[ {type: 'checkbox', fixed: 'left'} ,{field:'id', title:'ID', width:80, fixed: 'left', unresize: true, sort: true} ,{field:'loginName', title:'账户名', width:120, edit: 'text'} ,{field:'name', title:'用户名', width:150, edit: 'text', templet: function(res){ return '<em>'+ res.name +'</em>' }} ,{field:'pwd', title:'密码', width:80, edit: 'text', sort: true} ,{field:'rname', title:'角色名', width:100} ,{field:'right', title:'签名'} ]] ,page: true }); //头工具栏事件 //监听行工具事件 table.on('tool(test)', function(obj){ var row = obj.data; //console.log(obj) if(obj.event === 'del'){ layer.confirm('确认删除吗?', {icon: 3, title:'提示'}, function(index){ $.post('user.action',{ 'methodName':'del', 'id':row.id },function(rs){ if(rs.success){ //调用查询方法刷新数据 query(); }else{ layer.msg(rs.msg,function(){}); } },'json'); layer.close(index); }); } else if(obj.event === 'edit'){ edit("编辑"); } }); }
2.userEdit.js
let layer,form,$; layui.use(['layer','form','jquery'],function(){ layer=layui.layer,form=layui.form,$=layui.jquery; initData(); }); function initData(){ console.log(parent.row); if(null!=parent.row){ //因为layui.each内部的逻辑问题导致的所以要先深拷贝一份然后再去val //parent.row:表格行对象 form.val('user',$.extend({}, parent.row||{})); $('#name').attr('readonly','readonly'); } } function getData(){ return form.val('user'); }
3.index.js
var element,layer,util,$; layui.use(['element', 'layer', 'util'], function(){ element = layui.element ,layer = layui.layer ,util = layui.util ,$ = layui.$ $.ajax({ url:"{pageContext.request.contextPath}/permisson.action?methodName=menus", dataType:'json', success:function(data){ console.log(data); var htmlStr =''; $.each(data,function(i,n){ htmlStr+='<li class="layui-nav-item layui-nav-itemed">'; htmlStr+='<a class="" href="javascript:;">'+n.text+'</a>'; if (n.hasChildren) { var children=n.children; htmlStr+=' <dl class="layui-nav-child">'; $.each(children,function(idx,node){ htmlStr+=' <dd><a href="javascript:;" onclick="openTab(\''+node.text+'\',\''+node.attributes.self.url+'\',\''+node.id +'\')">'+node.text+'</a></dd>'; console.log(node.text); }); htmlStr+=' </dl>'; } htmlStr+='</li>'; console.log(n.text); }); $("#menu").html(htmlStr); element.render('menu'); } }); }); /** * */ function openTab(title,content,id) { var $node=$('li[lay-id="'+id+'"]') console.log($node); if ($node.length==0) { element.tabAdd('demo', { title: title ,content: "<iframe frameborder='0' src='"+content+"' scrolling='auto' style='width:100%;height:100%;'></iframe>" ,id: id //实际使用一般是规定好的id,这里以时间戳模拟下 }) } }
5.运行效果