代码:
package com.hy.fieldandvalue; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.apache.log4j.Logger; import com.hy.DBParam; class DbParam{ public final static String Driver = "oracle.jdbc.driver.OracleDriver"; public final static String DbUrl = "jdbc:oracle:thin:@127.0.0.1:1521:orcl"; public final static String User = "ufo"; public final static String Pswd = "1234"; } class KeyValue implements Comparable<KeyValue>{ String key; Object value; @Override public int compareTo(KeyValue another) { return this.key.compareTo(another.key); } } public class Fetcher { private static Logger log = Logger.getLogger(Fetcher.class); public static void main(String[] args) { Connection conn = null; Statement stmt = null; try{ Class.forName(DBParam.Driver).newInstance(); conn = DriverManager.getConnection(DBParam.DbUrl, DBParam.User, DBParam.Pswd); stmt = conn.createStatement(); //String sql = "select * from allocation_request where shipper_code='10005' and order_no='1911271000500004' and to_char(delivery_date,'yyyy-MM-dd')='2019-11-28'"; String sql="select * from testtb17 where id=114 "; ResultSet rs = stmt.executeQuery(sql); ResultSetMetaData rsMetadata = rs.getMetaData(); int count = rsMetadata.getColumnCount(); int index = 0; while (rs.next()) { index++; List<KeyValue> kvList=new ArrayList<KeyValue>(); for (int i=0; i<count; i++) { int idx=i+1; KeyValue kv=new KeyValue(); kv.key = rsMetadata.getColumnLabel(idx);// 列名 kv.value=rs.getString(kv.key); kvList.add(kv); } Collections.sort(kvList); System.out.println(); StringBuilder sb=new StringBuilder(); int idx=0; for(KeyValue kv:kvList) { idx++; sb.append(fixSizeStr("#"+idx,4)+fixSizeStr(kv.key,30)+kv.value+" "); } System.out.println(sb.toString()); } } catch (Exception e) { System.out.print(e.getMessage()); e.printStackTrace(); } finally { try { stmt.close(); conn.close(); } catch (SQLException e) { log.error("Can't close stmt/conn because of " + e.getMessage()); } } } /** * get a fix-length string,if less add space * @param str * @param size * @return */ private static String fixSizeStr(String str, int size) { return String.format("%-"+size+"s", str); } }
输出:
#1 AGE 0 #2 CREATEDTIME 2019-06-16 10:21:46 #3 ID 114 #4 NAME 0
--END-- 2019年12月4日20:26:01