Java program handles different database time types

 The biggest problem when dealing with time types is time types with time zones

For example, the following three time types of Oracle are types under the Oracle package and are not recognized by other databases.

import oracle.sql.TIMESTAMP;

import oracle.sql.TIMESTAMPLTZ;

import oracle.sql.TIMESTAMPTZ;

 

 Time type with time zone that needs to be converted into java:

java.time.OffsetDateTime;

Same for DateTimeOffset of sqlservice

/**
     * 将sql返回集转为 List<Map<String,Object>>,key:列名 Object:列值
     *
     * @param rs
     * @return
     */
    @Override
    public List<Map<String, Object>> getRs(ResultSet rs) {
        // 得到列的个数
        List<Map<String, Object>> datas = new ArrayList<Map<String, Object>>();
        try {
            ResultSetMetaData rsmd = rs.getMetaData();
            int colCount = rsmd.getColumnCount();
            // 因为要存储列的名字,所以要与列的个数相同
            String[] colNames = new String[colCount];

            /* 装上列的名字
             * getColumnLabel 别名
             * getColumnLabel()方法的索引是从1开始的。给最苦 写成从0开始,就抛了异常。
             */
            for (int i = 1; i <= colCount; i++) {
                colNames[i - 1] = rsmd.getColumnLabel(i);
            }

            // 这里的泛型声明也是有技巧的。
            HashMap<String, Object> data = null;

            // 把查询到的结果装入datas中
            while (rs.next()) {
                data = new HashMap<String, Object>();
                for (int i = 0; i < colCount; i++) {
                    //此种带时区的时间类型单独处理
                    if (object instanceof TIMESTAMPLTZ || object instanceof TIMESTAMPTZ) {
                        //        key             value
                        OffsetDateTime offsetDateTime = rs.getObject(colNames[m], OffsetDateTime.class);
                        data.put(colNames[m], offsetDateTime);
                    } else if (object instanceof TIMESTAMP) {
                        LocalDateTime localDateTime = rs.getObject(colNames[m], LocalDateTime.class);
                        data.put(colNames[m], localDateTime);
                    } else if (object instanceof DateTimeOffset) {
                        OffsetDateTime offsetDateTime = ((DateTimeOffset) object).getOffsetDateTime();
                        data.put(colNames[m], offsetDateTime);
                    } else {
                        //        key             value
                        data.put(colNames[m], object);
                    }
                }
                datas.add(data);
            }
        } catch (Exception e) {
            log.error(ExceptionUtil.getStackTrace(e));
            throw new DtsException(e.getMessage());
        }
        return datas;
    }

Guess you like

Origin blog.csdn.net/tck001221/article/details/132715175