1 24 25 package com.mckoi.util; 26 27 import java.sql.*; 28 import java.io.*; 29 import java.util.Vector ; 30 31 37 38 public class ResultOutputUtil { 39 40 41 45 private static void writeBreak(int[] widths, PrintWriter out) { 46 out.print('+'); 47 for (int i = 0; i < widths.length; ++i) { 48 int wid = widths[i] + 2; 49 for (int n = 0; n < wid; ++n) { 50 out.print('-'); 51 } 52 out.print('+'); 53 } 54 out.println(); 55 } 56 57 61 private static void writeRow(int[] widths, String [] cols, PrintWriter out) { 62 out.print('|'); 63 for (int i = 0; i < widths.length; ++i) { 64 String str = cols[i]; 65 out.print(' '); 66 out.print(str); 67 int wid = (widths[i] + 1) - str.length(); 69 for (int n = 0; n < wid; ++n) { 70 out.print(' '); 71 } 72 out.print('|'); 73 } 74 out.println(); 75 } 76 77 81 public static void formatAsText(ResultSet result_set, PrintWriter out) 82 throws SQLException { 83 ResultSetMetaData meta_data = result_set.getMetaData(); 84 int[] max_widths = new int[meta_data.getColumnCount()]; 86 Vector [] data = new Vector [meta_data.getColumnCount()]; 87 for (int i = 0; i < data.length; ++i) { 88 data[i] = new Vector (); 89 } 90 int row_count = 0; 91 92 for (int i = 0; i < data.length; ++i) { 93 String str = meta_data.getColumnLabel(i + 1); 94 max_widths[i] = Math.max(str.length(), max_widths[i]); 95 } 96 97 while (result_set.next()) { 99 for (int i = 0; i < data.length; ++i) { 100 Object ob = result_set.getObject(i + 1); 101 String str = "NULL"; 102 if (ob != null) { 103 str = ob.toString(); 104 } 105 data[i].addElement(str); 106 max_widths[i] = Math.max(str.length(), max_widths[i]); 107 } 108 ++row_count; 109 } 110 111 String [] line = new String [data.length]; 113 114 writeBreak(max_widths, out); 115 for (int n = 0; n < line.length; ++n) { 116 line[n] = meta_data.getColumnLabel(n + 1); 117 } 118 writeRow(max_widths, line, out); 119 writeBreak(max_widths, out); 120 for (int i = 0; i < row_count; ++i) { 121 for (int n = 0; n < line.length; ++n) { 122 line[n] = (String ) data[n].elementAt(i); 123 } 124 writeRow(max_widths, line, out); 125 } 126 writeBreak(max_widths, out); 127 128 } 129 130 131 } 132 | Popular Tags |