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);

    }

结语

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


版权声明:本文为bwl258wd原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。