目录

一、数据表格table 通过id来获取,动态获取

二、通过js动态获取数据表格数据,包括数据单元格的查看、编辑、删除

三、通过ajax实现局部刷新刷新(ajax异步请求)重点解决无法获取输入框的问题

四、Servlet+分页查询

五、封装json数据,不然 layui框架那边无法获取数据

六、底层数据逻辑以及实体类


一、数据表格table 通过id来获取,动态获取

<table  class="layui-hide" id="demo" lay-filter="test" >

二、通过js动态获取数据表格数据,包括数据单元格的查看、编辑、删除

<script type="text/html" id="barDemo">

<%--    <div class="layui-btn-container">--%>
<%--        <button type="button" class="layui-btn layui-btn-primary layui-btn-radius">原始按钮</button>--%>
<%--        <button type="button" class="layui-btn layui-btn-radius">默认按钮</button>--%>
<%--        <button type="button" class="layui-btn layui-btn-normal layui-btn-radius">百搭按钮</button>--%>
<%--        <button type="button" class="layui-btn layui-btn-warm layui-btn-radius">暖色按钮</button>--%>
<%--        <button type="button" class="layui-btn layui-btn-danger layui-btn-radius">警告按钮</button>--%>
<%--        <button type="button" class="layui-btn layui-btn-disabled layui-btn-radius">禁用按钮</button>--%>
<%--    </div>--%>
<%--layui-btn layui-btn-xs layui-btn-normal--%>
    <a class="layui-btn layui-btn-xs layui-btn-normal layui-btn-radius" lay-event="detail">查看</a>

    <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>

    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>

动态获取表格

<script src="/layui/layui.js"></script>
<script src="/layui/layui.all.js"></script>
<script src="/assets/js/jquery.js" type="text/javascript"></script>
<script src="/assets/js/jquery.form.js" type="text/javascript"></script>
<script src="/layuiadmin/layui/layui.all.js"></script>
<script src="/layuiadmin/layui/layui.js"></script>
<script type="text/javascript"></script>


 layui.use('table', function(){
        var table = layui.table;
        var dropdown = layui.dropdown;

        //第一个实例sousuo
        table.render({
            elem: '#demo'
            // ,toolbar: '#toolbarDemo'
            ,height: 'full-160'
            // ,height: 'full-200' // 最大高度减去其他容器已占有的高度差
            ,cellMinWidth: 100
            ,url: '/ceshi?action=query' //数据接口//直接调用不需要跳转

            ,page: true //开启分页
            // ,totalRow: true // 开启合计行得在前端传输数据:count//下面会多出空格//totalRowText: "合计"

            ,cols: [[ //表头

         {type: 'checkbox', fixed: 'left',width: 80,align: 'center',totalRowText: "合计"}
                ,{field: 'eId', title: '编号', width:80, sort: true, fixed: 'left'}
                ,{field: 'eAccount', title: '账户', width:80}
                ,{field: 'ePassword', title: '密码', width:80, sort: true}
                ,{field: 'eName', title: '姓名', width:80, sort: true}
                ,{field: 'eSex', title: '性别', width:80, sort: true}
                ,{field: 'eEducation', title: '学历', width:80, sort: true}
                ,{field: 'dName', title: '部门', width:120, sort: true}
                ,{field: 'ePosition', title: '职称', width:80, sort: true}
                ,{field: 'eIdcard', title: '身份证号码', width:180, sort: true}
                ,{field: 'ePhone', title: '手机号码', width:120, sort: true}
                ,{field: 'eAddress', title: '家庭地址', width:120, sort: true}
                ,{field: 'eEntrytime', title: '入职时间', width:120, sort: true}
                ,{fixed: 'right', title:'操作', width: 200, minWidth: 125, toolbar: '#barDemo'}
            ]]
            // , page:true
            ,limit:10
            ,limits:[5,10,20,30,40,50]
            , parseData: function (res) { //res 即为原始返回的数据
                console.log("成功"+res.status+";=="+res.message+";"+res.total);
                return {
                    "code": res.status, //解析接口状态
                    "msg": res.message, //解析提示文本
                    "count": res.total, //解析数据长度
                    "data": res.data //解析数据列表
                };
            }



            ,done: function(){
                var id = this.id;

              
            }
            ,error: function(res, msg){
                console.log(res, msg)
            }
        });

        // 工具栏事件
        table.on('toolbar(test)', function(obj){
            var id = obj.config.id;
            var checkStatus = table.checkStatus(id);
            var othis = lay(this);
            switch(obj.event){
                case 'getCheckData':
                    var data = checkStatus.data;
                    layer.alert(layui.util.escape(JSON.stringify(data)));
                    break;
                case 'getData':
                    var getData = table.getData(id);
                    console.log(getData);
                    layer.alert(layui.util.escape(JSON.stringify(getData)));
                    break;
                case 'isAll':
                    layer.msg(checkStatus.isAll ? '全选': '未全选')
                    break;
                case 'multi-row':
                    table.reload('test', {
                        // 设置行样式,此处以设置多行高度为例。若为单行,则没必要设置改参数 - 注:v2.7.0 新增
                        lineStyle: 'height: 95px;'
                    });
                    layer.msg('即通过设置 lineStyle 参数可开启多行');
                    break;
                case 'default-row':
                    table.reload('test', {
                        lineStyle: null // 恢复单行
                    });
                    layer.msg('已设为单行');
                    break;
                case 'LAYTABLE_TIPS':
                    layer.alert('Table for layui-v'+ layui.v);
                    break;
            };
        });

        //触发单元格工具事件
        table.on('tool(test)', function(obj){ // 双击 toolDouble
            var data = obj.data;//获取当前的行的数据
            //obj.data :获得 lay-event 对应的值(也可以是表头的 event 参数对应的值)
            console.log(obj.data)
            //console.log(obj)
            if(obj.event === 'detail'){ //查看

                layer.alert('编号:'+ data.eId +"<br/>"+'账户:'+data.eAccount+"<br/>"+'密码:'+data.ePassword+"<br/>"+
                    '姓名:' +data.eName+"<br/>"+'性别:' +data.eSex +"<br/>"+'学历:'+data.eEducation +"<br/>"+'部门:'
                    +data.dName +"<br/>"+'职称:'+data.ePosition +"<br/>"+'身份证号码:'+data.eIdcard +"<br/>"+'手机号码:'
                    +data.ePhone +"<br/>"+'家庭地址:'+data.eAddress +"<br/>"+'入职时间:'+data.eEntrytime);

            }else if(obj.event === 'del'){
                layer.confirm('真的删除员工吗?', function(index){
                    console.log(index)
                    console.log(data.eId)
                    obj.del();
                    // 	location.href="updatebyid?flag=all&eId="+eid;
                    // 	location.href="updatebyid?flag=all&eId="+eid+"&xxx"+xxx;
                    // location.href="updatetongyi?eId="+userId;
                    location.href = "/newsWork?action=delwork&eId="+data.eId;
                    layer.close(index);
                });
            } else if(obj.event === 'edit'){
                layer.open({
                    title: '编辑',
                    type: 1,
                    area: ['80%','80%'],
                    content: '<div class="site-text" style="margin: 5px; display: none" id="window"  target="test123">' +
                        '<form  action="/newsWork?action=add" method="post" class="layui-form" id="book"  lay-filter="example" style="margin: 25px;width: 500px"> ' +
                        '<div class="layui-form-item"> ' +
                        '<div class="layui-col-md6">' +
                        '<label class="layui-form-label" >账号</label> ' +
                        '<div class="layui-input-block"> ' +
                        '<input type="text" id="bid" name="eAccount" lay-verify="title" autocomplete="off" placeholder="请输入账号"  class="layui-input"> ' +
                        '</div> </div>' +
                        '<div class="layui-col-md6">' +
                        '<div class="layui-form-item"> ' +
                        '<label class="layui-form-label">姓名</label> ' +
                        '<div class="layui-input-block"> ' +
                        '<input type="text" id="name" name="eName" lay-verify="title" autocomplete="off" placeholder="请输入姓名" class="layui-input"> ' +
                        '</div> </div> </div> </div> ' +
                        '<div class="layui-form-item"> ' +
                        '<div class="layui-col-md6"> ' +
                        '<label class="layui-form-label" >性别</label> ' +
                        '<div class="layui-input-block"> ' +
                        '<select id="select" class="form-control"  name="eSex" style="width:212px;height:38px;" > ' +
                        '<option value="">请选择</option> ' +
                        '<option value="男">男</option> ' +
                        '<option value="女">女</option> ' +
                        '</select> </div> </div> ' +
                        '<div class="layui-col-md6"> ' +
                        '<div class="layui-form-item"> ' +
                        '<label class="layui-form-label">学历</label> ' +
                        '<div class="layui-input-block"> ' +
                        '<select id="select2" name="eEducation" class="form-control" style="width:212px;height:38px;" > ' +
                        '<option value="">请选择</option>  ' +
                        '<option value="硕士">硕士</option> ' +
                        '<option value="本科">本科</option> ' +
                        '<option value="大专">大专</option> ' +
                        '<option value="高中">高中</option> ' +
                        '<option value="小学">小学</option> </select> </div> </div> </div> </div> ' +
                        '<div class="layui-form-item"> <div class="layui-col-md6"> ' +
                        '<label class="layui-form-label" >部门</label> ' +
                        '<div class="layui-input-block"> ' +
                        '<select id="select" class="form-control"  name="dDid" style="width:212px;height:38px;" > ' +
                        '<option value="">请选择</option> ' +
                        '<option value="1">新闻审核部</option> ' +
                        '<option value="2">人力资源部</option> ' +
                        '<option value="后勤管理部">后勤管理部</option> ' +
                        '<option value="技术研发部">技术研发部</option> ' +
                        '<option value="市场营销部">市场营销部</option> ' +
                        '</select> </div></div>' +
                        ' <div class="layui-col-md6"> <div class="layui-form-item"> ' +
                        '<label class="layui-form-label">职位</label> ' +
                        '<div class="layui-input-block"> ' +
                        '<select id="select2" name="ePosition" class="form-control" style="width:212px;height:38px;"  > ' +
                        '<option value="">请选择</option> ' +
                        '<option value="经理">经理</option> ' +
                        '<option value="副经理">副经理</option> ' +
                        '<option value="总监">总监</option> ' +
                        '<option value="副总监">副总监</option> ' +
                        '<option value="普通员工">普通员工</option> </select> </div></div></div> </div> ' +
                        '<div class="layui-form-item"> ' +
                        '<div class="layui-col-md6"> ' +
                        '<label style="float:left;display:block;padding-top: 9px;padding-bottom:9px; padding-right:-25px;width:100px;font-weight:400;line-height:20px;text-align:right">身份证号码</label> ' +
                        '<div class="layui-input-block"> ' +
                        '<input type="text" id="id" name="eIdcard" lay-verify="title" autocomplete="off" placeholder="请输入身份证号码" class="layui-input"> ' +
                        '</div> ' +
                        '</div> ' +
                        '<div class="layui-col-md6">' +
                        ' <div class="layui-form-item"> ' +
                        '<label class="layui-form-label">入职时间</label> ' +
                        '<div class="layui-input-block"> ' +
                        '<input id="test2" type="text"  name="eEntrytime" lay-verify="title" autocomplete="off" placeholder="请选择入职时间" class="layui-input"> ' +
                        '</div> ' +
                        '</div></div> </div> ' +
                        '<div class="layui-form-item"> <div class="layui-col-md6"> ' +
                        '<label class="layui-form-label" >手机号码</label> ' +
                        '<div class="layui-input-block"> ' +
                        '<input type="text" id="ePhone" name="ePhone" lay-verify="title" autocomplete="off" placeholder="请输入手机号码"  class="layui-input"> ' +
                        '</div> </div> ' +
                        '<div class="layui-col-md6"> ' +
                        '<div class="layui-form-item"> ' +
                        '<label class="layui-form-label">家庭地址</label> ' +
                        '<div class="layui-input-block"> ' +
                        '<input type="text" id="eAddress" name="eAddress" lay-verify="title" autocomplete="off" placeholder="请输入家庭地址" class="layui-input"> ' +
                        '</div> </div> </div> </div> ' +
                        '<div class="layui-form-item" style="float: left;margin-left: 250px"> ' +
                        '<div class="layui-input-block"> ' +
                        '<button class="layui-btn layui-btn-normal" lay-submit="" lay-filter="demo1">确认</button> ' +
                        '</div> ' +
                        '</div> ' +
                        '<button href="/queryStaff" type="button" class="layui-btn layui-btn-primary" style="float: left;margin-left: 10px">返回</button> ' +
                        '</form> </div>'
                });
            }
        });

        //触发表格复选框选择
        table.on('checkbox(test)', function(obj){
            console.log(obj)
        });

        //触发表格单选框选择
        table.on('radio(test)', function(obj){
            console.log(obj)
        });

        // 行单击事件
        table.on('row(test)', function(obj){
            //console.log(obj);
            //layer.closeAll('tips');
        });
        // 行双击事件
        table.on('rowDouble(test)', function(obj){
            console.log(obj);
        });

        // 单元格编辑事件
        table.on('edit(test)', function(obj){
            var field = obj.field //得到字段
                ,value = obj.value //得到修改后的值
                ,data = obj.data; //得到所在行所有键值

            var update = {};
            update[field] = value;
            obj.update(update);
        });
    });

三、通过ajax实现局部刷新刷新(ajax异步请求)重点解决无法获取输入框的问题

 <div style="float:left;margin-left:600px;margin-bottom: 20px;margin-top: 20px">
<%--<textarea name="comment" id="message" placeholder="请注意评论礼仪!"></textarea>--%>
     <input   id="serch" type="text" name="eName"  required lay-verify="required" placeholder="请输入员工姓名" autocomplete="off" class="layui-input">
  </div>
      <button type="submit" id="123" class="layui-btn layui-btn-normal layui-btn-radius" style="float:left;margin-left:15px;margin-top: 20px">搜索</button>
layui.use(['form', 'jquery', 'layer'], function () {


            var form = layui.form;
            var $ = layui.$;
            var layer = layui.layer;
            let serch = $("#serch").val();
            //通过点击事件获取。不然获取不了input里面的值
            $(function () {
                $("#123").click(function () {
                    // alert($("textarea[name='comment']").val());
                    // console.log($("textarea[name='comment']").val())
                    alert($("input[name='eName']").val());
                    console.log($("input[name='eName']").val())
                    let action = $("input[name='eName']").val()
                    console.log(action)
                    $.ajax( {

                        url    :  "/ceshi?action=mohu&eName="+action,  // 要提交的URL路径
                        type    :  "post",    // 发送请求的方式
                        // 要发送到服务器的数据
                        dataType:  "JSON",     // 指定传输的数据格式
                        beforeSend: function() {     //请求之前的方法
                        },
                        success  :  function(result) {
                            let d = result;
                            console.log(result)
                            console.log(d)
                            console.log(d.data.eId)
                            console.log(result.data.eId)
                            layui.use(['form','jquery','table','layer'],function(){
                                var form = layui.form;
                                var $ = layui.jquery;
                                var table = layui.table;
                                var layer = layui.layer;

                                table.render({
                                    elem:"#demo",
                                    data:d
                                    ,height: 'full-160'
                               // ,height: 'full-200' // 最大高度减去其他容器已占有的高度差
                                    ,cellMinWidth: 100
                                    ,page: true, //开启分页c
                                    url    :  "/ceshi?action=mohu&eName="+action,//调用接
                                    cols: [[ //表头
                         {
   type: 'checkbox', fixed: 'left',width: 80,align: 'center',totalRowText: "合计"}
   ,{field: "eId", title: '编号', width:80, sort: true, fixed: 'left'}
   ,{field: 'eAccount', title: '账户', width:80}
   ,{field: 'ePassword', title: '密码', width:80, sort: true}
   ,{field: 'eName', title: '姓名', width:80, sort: true}
   ,{field: 'eSex', title: '性别', width:80, sort: true}
    ,{field: 'eEducation', title: '学历', width:80, sort: true}
    ,{field: 'dName', title: '部门', width:120, sort: true}
   ,{field: 'ePosition', title: '职称', width:80, sort: true}
     ,{field: 'eIdcard', title: '身份证号码', width:180, sort: true}
    ,{field: 'ePhone', title: '手机号码', width:120, sort: true}
     ,{field: 'eAddress', title: '家庭地址', width:120, sort: true}
     ,{field: 'eEntrytime', title: '入职时间', width:120, sort: true}
       ,{fixed: 'right', title:'操作', width: 200, minWidth: 125, toolbar: '#barDemo'}
                                ]],
                                    parseData: function(d) { //res 即为原始返回的数据
                                        return {
                                            "code": 0, //解析接口状态
                                            "msg": "ok", //解析提示文本
                                            "count": 100, //解析数据长度
                                            "data": d //解析数据列表
                                        }
                                    }
                                });
                            });
                            // 请求成功后要执行的代码
                            console.log("成功")
                        },
                        error       :  function() {           // 请求失败后要执行的代码
                            console.log("失败")
                        }
                    } );
                })
            })

            // let aaa =$("textarea[name='comment']").val()
            // console.log($("textarea[name='comment']").val())
            // console.log("=="+aaa)
            // console.log(serch)
            // console.log(form)
            // console.log(form)
            // console.log(form)
            // console.log($("[name='eName']").val())
            // var a=  document.getElementById("chaxun").innerText
            // var a=  document.getElementById("chaxun").innerHTML
            // alert(a);
            // console.log("xx")
            // console.log(a)
            // console.log("xx")
            // console.log("xx")


    });

四、Servlet+分页查询

package com.lingnan.servlet;

import com.alibaba.fastjson.JSON;
import com.lingnan.dao.impl.NewsWorkersDaoImpl;
import com.lingnan.pojo.DataJson;
import com.lingnan.pojo.NewsWorker;
import com.lingnan.pojo.TableJson;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @author :小邓
 * @date :Created in 2022/7/4 14:58
 * @description:单单
 * @modified By:
 * @version: 1.0
 */
@WebServlet("/ceshi")
public class ceshiServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String action = req.getParameter("action");
        System.out.println(action);
        String page = req.getParameter("page");
        String limit = req.getParameter("limit");
        System.out.println("第几页"+page+"几条"+limit);
        if ( action.equals("mohu") ){
            req.setCharacterEncoding("UTF8");
            req.setCharacterEncoding("utf-8");//设置请求的编码格式为gb2312
            resp.setContentType("text/html;charset=utf-8");//解决插入乱码问题顺序要放好
            String eName = req.getParameter("eName");
            System.out.println(eName);
            List<NewsWorker> newsWorkers = new NewsWorkersDaoImpl().queryWorkByName(eName);
            List<NewsWorker> workers = new ArrayList<>();
            for ( int j = 0;j<newsWorkers.size();j++ ){
                if ( newsWorkers.get(j).getFlag()==0 ){
                    System.out.println(newsWorkers.get(j).getFlag()==0);
                    workers.add(newsWorkers.get(j));
                }
            }
            TableJson<NewsWorker> objectTableJson = new TableJson<>();

            //封装json
            objectTableJson.setCode(0);
            objectTableJson.setMsg("OK");
//            objectTableJson.setData(newsWorkers);
            objectTableJson.setData(workers);
            objectTableJson.setCount(workers.size());
            System.out.println(objectTableJson);

            String s = JSON.toJSONString(objectTableJson);//转换为json数据
            PrintWriter writer = resp.getWriter();
            writer.println(s);
//            TableJson<NewsWorker> objectTableJson = new TableJson<>();
//            //封装json
//            objectTableJson.setCode(0);
//            objectTableJson.setMsg("OK");
//            objectTableJson.setData(newsWorkers);
//            objectTableJson.setCount(newsWorkers.size());
//            System.out.println(objectTableJson);
//            String s = JSON.toJSONString(objectTableJson);//转换为json数据
//            PrintWriter writer = resp.getWriter();
//            writer.println(s);



        }else {
            req.setCharacterEncoding("UTF8");
            req.setCharacterEncoding("utf-8");//设置请求的编码格式为gb2312
            resp.setContentType("text/html;charset=utf-8");//解决插入乱码问题顺序要放好
            //解决网页乱码的问题
            List<NewsWorker> newsWorkers = new NewsWorkersDaoImpl().queryWork();
            int size = newsWorkers.size();
            System.out.println("数据:"+size);

            List<NewsWorker> workers = new ArrayList<>();//新建一个数组来存放分页查询的数据
            
            int x = Integer.parseInt(page) * Integer.parseInt(limit)-Integer.parseInt(limit);
            System.out.println(x);
            for(int i = x;(i<size) && ((i-x)<Integer.parseInt(limit));i++){
                //按在也是获取数据把它加入新建的数组里面
//                System.out.println(i);
//                System.out.println(newsWorkers.get(i));
                if ( newsWorkers.get(i).getFlag()==0 ){
                    System.out.println(newsWorkers.get(i).getFlag()==0);
                workers.add(newsWorkers.get(i));
                }
            }

            TableJson<NewsWorker> objectTableJson = new TableJson<>();

            //封装json
            objectTableJson.setCode(0);
            objectTableJson.setMsg("OK");
//            objectTableJson.setData(newsWorkers);
            objectTableJson.setData(workers);
            objectTableJson.setCount(workers.size());
            System.out.println(objectTableJson);

            String s = JSON.toJSONString(objectTableJson);//转换为json数据
            PrintWriter writer = resp.getWriter();
            writer.println(s);//把json数据传输到网页中

        }


    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req,resp);
    }
}

五、封装json数据,不然 layui框架那边无法获取数据

package com.lingnan.pojo;

import lombok.Data;

import java.util.List;
import java.util.Map;

/**
 * @author :小邓
 * @date :Created in 2022/7/2 12:38
 * @description:11
 * @modified By:
 * @version: 1.0
 */
@Data
public class TableJson<T> {
    private Integer code ;
    private String msg ;
    private List<T> data;
    private int count;

}

六、底层数据逻辑以及实体类

package com.lingnan.dao.impl;

import com.lingnan.dao.NewsWorkersDao;
import com.lingnan.pojo.NewsWorker;
import com.lingnan.util.DataBase;

import javax.servlet.http.HttpServlet;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author :小邓
 * @date :Created in 2022/7/3 14:07
 * @description:shitilei
 * @modified By:
 * @version: 1.0
 */
public class NewsWorkersDaoImpl implements NewsWorkersDao {
    @Override
    public List<NewsWorker> queryWork() {
       List<NewsWorker> list = new ArrayList<NewsWorker>();
        String sql = "select e_id, e_account, e_password, e_name, e_sex, e_education,d_name, e_position, e_idcard, " +
                " e_phone, e_address, e_entrytion, e_role,flag" +
                " from news_worker inner join news_department on news_worker.d_id = news_department.d_id";
//        String sql="select  * from news_worker";
        ResultSet rs= DataBase.myQuery(sql, null);

        try {
            while (rs.next()){
                //必须得放在里面,不然只是存储最后一条
                NewsWorker allwork = new NewsWorker();

                allwork.setEId(rs.getInt("e_id"));
//                System.out.println(rs.getInt("e_id"));
                allwork.setEAccount(rs.getString("e_account"));
                allwork.setEPassword(rs.getString("e_password"));
                allwork.setEName(rs.getString("e_name"));
                allwork.setESex(rs.getString("e_sex"));
                allwork.setEEducation(rs.getString("e_education"));
                allwork.setDName(rs.getString("d_name"));
                allwork.setEPosition(rs.getString("e_position"));
                allwork.setEIdcard(rs.getString("e_idcard"));
                allwork.setEPhone(rs.getString("e_phone"));
                allwork.setEAddress(rs.getString("e_address"));
                allwork.setEEntrytime(rs.getString("e_entrytion"));
                allwork.setERole(rs.getInt("e_role"));
                allwork.setFlag(rs.getInt("flag"));
                list.add(allwork);
//                System.out.println(allwork);

            }
        }
        catch (SQLException e) {
            e.printStackTrace();
        }

        return list;
    }

    @Override
    public int insertWork(NewsWorker newsWorker) {
        String sql = "insert into news_worker\n" +
                "    (e_id,e_account, e_password, e_name, e_sex,\n" +
                "     e_education, d_id, e_position, e_idcard,\n" +
                "     e_phone, e_address, e_entrytion) values (?,?,?,?,?,?,?,?,?,?,?,?)";
        Object [] parms ={ newsWorker.getEId(),newsWorker.getEAccount(),newsWorker.getEPassword(),newsWorker.getEName(),
                            newsWorker.getESex(),newsWorker.getEEducation(),newsWorker.getDDid(),
                            newsWorker.getEPosition(),newsWorker.getEIdcard(),newsWorker.getEPhone(),
                            newsWorker.getEAddress(),newsWorker.getEEntrytime()};
        return DataBase.executeUpdateAll(sql,parms);


    }

    @Override
    public int deleteWork(String eId) {
        String sql = "delete  from news_worker where e_id=?";
        Object [] parms = {eId};
        return DataBase.executeUpdateAll(sql,parms);
    }

    @Override
    public int deleteHuishouWork(int flag,String eId) {
        String sql = "update news_worker set flag = ? where e_id = ?";
        Object [] parms = {flag,eId};
        return DataBase.executeUpdateAll(sql,parms);
    }

    @Override
    public List<NewsWorker> queryWorkByName(String eName) {
        List<NewsWorker> list = new ArrayList<NewsWorker>();
        String sql = "select e_id, e_account, e_password, e_name, e_sex, e_education,d_name, e_position, e_idcard,e_phone, e_address, e_entrytion, e_role,flag from news_worker inner join news_department on news_worker.d_id = news_department.d_id where e_name like '%" + eName+ "%'";
//        String sql = "select e_id, e_account, e_password, e_name, e_sex, e_education,d_name, e_position, e_idcard,e_phone, e_address, e_entrytion, e_role,flag from news_worker inner join news_department on news_worker.d_id = news_department.d_id where e_name like %?%";
        System.out.println(sql);
        //        String sql = "select * from staff where sname like '%" + sname+ "%'";
//        Object[] parms = {eName};
        ResultSet rs= DataBase.myQuery(sql, null);
//        ResultSet rs= DataBase.myQuery(sql, eName);

        try {
            while (rs.next()){
                //必须得放在里面,不然只是存储最后一条
                NewsWorker allwork = new NewsWorker();
                allwork.setEId(rs.getInt("e_id"));
//                System.out.println(rs.getInt("e_id"));
                allwork.setEAccount(rs.getString("e_account"));
                allwork.setEPassword(rs.getString("e_password"));
                allwork.setEName(rs.getString("e_name"));
                allwork.setESex(rs.getString("e_sex"));
                allwork.setEEducation(rs.getString("e_education"));
                allwork.setDName(rs.getString("d_name"));
                allwork.setEPosition(rs.getString("e_position"));
                allwork.setEIdcard(rs.getString("e_idcard"));
                allwork.setEPhone(rs.getString("e_phone"));
                allwork.setEAddress(rs.getString("e_address"));
                allwork.setEEntrytime(rs.getString("e_entrytion"));
                allwork.setERole(rs.getInt("e_role"));
                allwork.setFlag(rs.getInt("flag"));
                list.add(allwork);
//                System.out.println(allwork);

            }
        }
        catch (SQLException e) {
            e.printStackTrace();
        }

        return list;
    }
}
package com.lingnan.pojo;

import lombok.Data;

/**
 * @author :小邓
 * @date :Created in 2022/7/3 12:47
 * @description:员工表实体类
 * @modified By:
 * @version: 1.0
 */
@Data
public class NewsWorker {
    private int eId;//员工编号
    //使用小辣椒会把首字母变成大写
    private String eAccount;//员工账号
    private String ePassword;//员工密码
    private String eName;//员工姓名
    private String eSex;//性别
    private String eEducation;//学历
    private int dDid;//部门id
    private String dName;//部门名称
    private String ePosition;//职称
    private String eIdcard;//身份证号码
    private String ePhone;//手机号码
    private String eAddress;//家庭地址
    private String eEntrytime;//入职时间
    private int eRole;//权限
    private int flag;//删除字段判断

}

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐