JDBC方式update,参数完全动态化

实例代码

public static void main(String[] args) {
        //公共使用的两个集合,为了保证 column 和 value 的顺序保持一致,需要用到有序Map存放数据
        Map<String, Object> setValueMap = new LinkedHashMap<>();
        Map<String, Object> whereOptionMap = new LinkedHashMap<>();

        setValueMap.put("name", "张三");
        setValueMap.put("age", 11);
        setValueMap.put("sex", "男");
        setValueMap.put(null, "");

        //原条件
        whereOptionMap.put("name", "gyl");
        whereOptionMap.put("age", 12);
        whereOptionMap.put(null, "123");
        whereOptionMap.put("sex", "女");
        whereOptionMap.put(null, "");
        whereOptionMap.put("phone", null);

        setValueMap.remove(null);
        whereOptionMap.remove(null);

        System.out.println("setValueMap = " + setValueMap);
        System.out.println("whereOptionMap = " + whereOptionMap);


        //拼接setValue
        StringJoiner setSQL = new StringJoiner(",", "set ", " ");
        setValueMap.keySet().forEach(item -> setSQL.add(item + "=?"));
        //拼接whereOption条件字符串
        StringJoiner whereSQL = new StringJoiner(" and ", "where ", " ");
        whereOptionMap.keySet().forEach(item -> whereSQL.add("nvl(" + item + ",'defaultValue')=nvl(?,'defaultValue')"));

        System.out.println(setSQL);
        System.out.println(whereSQL);

        // 将两个集合的value值拼接,而后转成Object[]数组

        System.out.println(setValueMap.values());
        System.out.println(whereOptionMap.values());
        ArrayList<Object> values = ListUtil.toList(setValueMap.values());
        values.addAll(whereOptionMap.values());
        System.out.println(values);
        Object[] params = values.toArray();


        //每次for循环用完之后清空掉
        setValueMap.clear();
        whereOptionMap.clear();

    }

参考结果

setValueMap = {name=张三, age=11, sex=男}
whereOptionMap = {name=gyl, age=12, sex=女, phone=null}
set name=?,age=?,sex=? 
where nvl(name,'defaultValue')=nvl(?,'defaultValue') and nvl(age,'defaultValue')=nvl(?,'defaultValue') and nvl(sex,'defaultValue')=nvl(?,'defaultValue') and nvl(phone,'defaultValue')=nvl(?,'defaultValue') 
[张三, 11, 男]
[gyl, 12, 女, null]
[张三, 11, 男, gyl, 12, 女, null]
posted @   iullor  阅读(306)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
历史上的今天:
2021-09-22 通过SQL语句 获取 MySQL信息
点击右上角即可分享
微信分享提示