uopspop

Untitled

Oct 7th, 2016
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.59 KB | None | 0 0
  1. package connectionPool;
  2.  
  3. import java.sql.*;
  4.  
  5. public class HtmlSQLResult {
  6.     private String sql;
  7.     private Connection con;
  8.  
  9.     public HtmlSQLResult(String sql, Connection con) {
  10.         this.sql = sql;
  11.         this.con = con;
  12.     }
  13.  
  14.     public String toString() { // can be called at most once
  15.         StringBuffer out = new StringBuffer();
  16.  
  17.         // Uncomment the following line to display the SQL command at start of
  18.         // table
  19.         // out.append("Results of SQL Statement: " + sql + "<P>\n");
  20.  
  21.         try {
  22.             Statement stmt = con.createStatement();
  23.  
  24.             if (stmt.execute(sql)) {
  25.                 // There's a ResultSet to be had
  26.                 ResultSet rs = stmt.getResultSet();
  27.                 out.append("<TABLE border=1 bordercolor=red>\n");
  28.  
  29.                 ResultSetMetaData rsmd = rs.getMetaData();
  30.  
  31.                 int numcols = rsmd.getColumnCount();
  32.  
  33.                 // Title the table with the result set's column labels
  34.                 out.append("<TR>");
  35.                 for (int i = 1; i <= numcols; i++)
  36.                     out.append("<TH>" + rsmd.getColumnLabel(i));
  37.                 out.append("</TR>\n");
  38.  
  39.                 while (rs.next()) {
  40.                     out.append("<TR>"); // start a new row
  41.                     for (int i = 1; i <= numcols; i++) {
  42.                         out.append("<TD>"); // start a new data element
  43.                         Object obj = rs.getObject(i);
  44.                         if (obj != null) {
  45.                             out.append(obj.toString());
  46.                         }
  47.  
  48.                     }
  49.                     out.append("</TR>\n");
  50.                 }
  51.  
  52.                 // End the table
  53.                 out.append("</TABLE>\n");
  54.             } else {
  55.                 // There's a count to be had
  56.                 out.append("<B>Records Affected:</B> " + stmt.getUpdateCount());
  57.             }
  58.         } catch (SQLException e) {
  59.             out.append("</TABLE><H1>ERROR:</H1> " + e.getMessage());
  60.         }
  61.  
  62.         return out.toString();
  63.     }
  64. }
Add Comment
Please, Sign In to add comment