1 package net.jaekl.squelch.stmt;
3 import java.io.IOException;
4 import java.io.PrintWriter;
5 import java.sql.Connection;
6 import java.sql.PreparedStatement;
7 import java.sql.ResultSet;
8 import java.sql.ResultSetMetaData;
9 import java.sql.SQLException;
10 import java.util.Locale;
12 import net.jaekl.squelch.sql.Column;
14 public class Select extends Query {
17 public boolean handles(String line) {
22 String s = line.trim().toUpperCase(Locale.CANADA);
23 return (s.startsWith("SELECT "));
27 public int exec(Connection conn, PrintWriter pw, String line) throws IOException, SQLException
31 try (PreparedStatement ps = conn.prepareStatement(line))
33 try (ResultSet rs = ps.executeQuery())
35 rowCount = printFormatted(pw, rs);
42 private Column[] getColumns(ResultSetMetaData metaData)
43 throws SQLException, ClassNotFoundException
45 int colCount = metaData.getColumnCount();
47 Column cols[] = new Column[colCount];
48 for (int idx = 1; idx <= colCount; ++idx) {
49 String label = metaData.getColumnLabel(idx);
50 Class<?> clazz = Class.forName(metaData.getColumnTypeName(idx));
51 int width = metaData.getColumnDisplaySize(idx);
52 cols[idx] = new Column(label, clazz, width);
58 private int printFormatted(PrintWriter pw, ResultSet rs) throws IOException, SQLException
61 ResultSetMetaData metaData = rs.getMetaData();
63 Column[] cols = getColumns(metaData);
64 StringBuilder sb = new StringBuilder();
65 sb.append("----------------------------------\n");
66 for (int idx = 1; idx <= cols.length; ++idx) {
67 sb.append("|" + cols[idx - 1].getLabel());
70 String header = sb.toString();
78 for (int idx = 1; idx <= cols.length; ++idx) {
79 pw.print("|" + rs.getObject(idx));
84 pw.println("----------------------------------");
86 pw.println("" + rowCount + " row(s) returned.");
90 catch (ClassNotFoundException exc) {
91 throw new SQLException(exc);