00001 import java.sql.Connection;
00002 import java.sql.Statement;
00003 import java.sql.ResultSet;
00004 import java.sql.SQLException;
00005 import java.io.PrintWriter;
00006
00007
00008
00009
00010
00011
00012 public class Query
00013 {
00014 public Statement s;
00015 public ResultSet r;
00016 public PrintWriter pw;
00017
00018 public static final boolean DEBUG = false;
00019
00020 public Query(Connection conn, PrintWriter pw)
00021 {
00022 this(conn, pw, null);
00023 }
00024
00025 public Query(Connection conn, PrintWriter pw, String sql)
00026 {
00027 this.pw = pw;
00028 try
00029 {
00030 s = conn.createStatement();
00031 if (sql != null) query(sql);
00032 }
00033 catch(SQLException e)
00034 {
00035 Widget.ShowException(e, pw);
00036 }
00037 }
00038
00039 public void execute(String sql)
00040 {
00041 if (DEBUG) printSql(sql);
00042 try
00043 {
00044 s.executeUpdate(sql);
00045 }
00046 catch (SQLException e)
00047 {
00048 pw.println("<h2>Failed to execute SQL Statement:</h2>");
00049 printSql(sql);
00050 Widget.ShowException(e, pw);
00051 }
00052 }
00053
00054 public void query(String sql)
00055 {
00056 if (DEBUG) printSql(sql);
00057 try
00058 {
00059 if (r != null) r.close();
00060 r = s.executeQuery(sql);
00061 }
00062 catch (SQLException e)
00063 {
00064 pw.println("<h2>Failed to execute SQL Query:</h2>");
00065 printSql(sql);
00066 Widget.ShowException(e, pw);
00067 }
00068 }
00069
00070 public void printSql(String sql)
00071 {
00072 pw.println("<pre style=\"background-color: #EEEEEE\">" + sql + "</pre>");
00073 }
00074
00075 public void close()
00076 {
00077 try
00078 {
00079 try
00080 {
00081 if (r != null)
00082 {
00083 r.close();
00084 r = null;
00085 }
00086 }
00087 finally
00088 {
00089 s.close();
00090 s = null;
00091 }
00092 }
00093 catch (SQLException e)
00094 {
00095 Widget.ShowException(e, pw);
00096 }
00097 }
00098
00099 public static void rethrow(Throwable e)
00100 {
00101 if (e instanceof RuntimeException)
00102 throw (RuntimeException) e;
00103 if (e instanceof Error)
00104 throw (Error) e;
00105 else
00106 throw new Error("Unknown Exception caught", e);
00107 }
00108 };