java原生代码实现行转列

背景

大家应该都用过数据库自带的内置函数PIVOT和UNPIVOT来进行行列的互相转化,但是当我们在做数据转储的时候,如果这个动作是集成在自动化服务当中,想用java代码直接实现从源数据读出数据,经过转储以后直接插入目标表中,能不能实现呢?今天我们就来尝试一下!

方案

源表:

abqty_2022_04_26qty_2022_04_27qty_2022_04_28
aabb112233

目标表:

abqty_dateqty
aabb2022_04_2611
aabb2022_04_2722
aabb2022_04_2833

我们所要实现的就是把源表经过行转列处理后变成目标表的格式,话不多说,直接上才艺。

code

public void test(Connection conn, String table, String Condition) throws SQLException, ClassNotFoundException {
        ResultSet input_rs;
        Statement st = conn.createStatement();

        if (ObjectUtils.isEmpty(Condition)) {
            Condition = "1=1";
        }
        String sql = "SELECT * FROM tableName where " + Condition;
        input_rs = st.executeQuery(sql);

        saveTable(input_rs);

        input_rs.close();
        conn.close();
    }
public void saveTable(ResultSet input_rs) throws SQLException, ClassNotFoundException {
        ResultSetMetaData rsmdl = input_rs.getMetaData();
        Connection con = JDBCUtil.getConnection();
        con.setAutoCommit(false);
        String insert = "insert into dbo.targetTable values(?,?,?,?,?,?,?,?,?) ";
        PreparedStatement ps = con.prepareStatement(insert);
        Map<Integer, String> qtyColumnMap = new HashMap<>();
        ResultSetMetaData rsmd = input_rs.getMetaData();
        for (int i = 1; i <= rsmd.getColumnCount(); i++) {
            String columnName = rsmd.getColumnName(i);
            if (columnName.startsWith("QTY_")) {
                qtyColumnMap.put(i, columnName);
            }
        }


        int count = rsmdl.getColumnCount();
        int i = 0;
        while (input_rs.next()) {
            List<String> newColumn = new ArrayList<>();
            for (int j = 1; j <= count; j++) {
                if (Objects.nonNull(qtyColumnMap.get(j))) {
                    for (int k = 1; k <= newColumn.size(); k++) {
                        ps.setString(k, newColumn.get(k - 1));
                    }
                    ps.setString(newColumn.size() + 1, qtyColumnMap.get(j).substring("QTY_".length())); // qty_date
                    ps.setFloat(newColumn.size() + 2, input_rs.getFloat(j)); // qty
                    ps.addBatch();
                    i++;
                } else {
                    newColumn.add(input_rs.getString(j));
                }
            }

            if (i >= 2000) {
                ps.executeBatch();
                con.commit();
                ps.clearBatch();
                i = 0;
            }

        }

        ps.executeBatch();
        con.commit();
        ps.clearBatch();
        JDBCUtil.close(ps, con);

    }

结语

希望上面的方案可以为您带来帮助,共勉!!!

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值