00001 package net.threebit.utils.sosc;
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022 import java.io.*;
00023 import java.sql.*;
00024 import java.util.*;
00025
00029 public class DbTool {
00030
00031 protected Connection connection;
00032 private String className;
00033 private String url;
00034 private String userName;
00035 private String password;
00036 private boolean connectionIsPrivate = true;
00037
00041 public DbTool (String className, String url, String userName, String password) throws Exception {
00042 setConnection(className, url, userName, password);
00043 }
00044
00048 public DbTool (Connection connection) throws Exception {
00049 setConnection(connection);
00050 }
00051
00055 private void setConnection (Connection connection) throws SQLException {
00056 if (this.connection != null) {
00057 this.connection.close();
00058 }
00059 this.connection = connection;
00060 }
00061
00065 private void setConnection (String className, String url, String userName, String password) throws Exception {
00066 this.className = className;
00067 this.url = url;
00068 this.userName = userName;
00069 this.password = password;
00070 Class.forName(className);
00071 setConnection(DriverManager.getConnection(url,userName,password));
00072 }
00073
00077 public Connection getConnection() throws Exception {
00078
00079 connectionIsPrivate = false;
00080 return connection;
00081 }
00082
00086 public String getUserName() {
00087 return userName;
00088 }
00089
00090
00091 public void close () throws Exception {
00092 connection.close();
00093 }
00094
00095 public void rollback () throws Exception {
00096 connection.rollback();
00097 }
00098
00099 public void commit () throws Exception {
00100 connection.commit ();
00101 }
00102
00103 public void setAutoCommit( boolean autocommit ) throws Exception {
00104
00105 connection.setAutoCommit( autocommit );
00106 }
00114 public String q (Object o) {
00115 if (o == null) { return "''"; }
00116 String field = o.toString() ;
00117 if (field.length() == 0) { return "''"; }
00118
00119 if (field.indexOf('\'')>-1) {
00120
00121 char[] origin= new char[field.length()];
00122 field.getChars(0,field.length(),origin,0);
00123 int numApostrophes=0;
00124 for (int f=0;f<origin.length; f++) {
00125 if (origin[f]=='\'') numApostrophes++;
00126 }
00127 char[] parsed= new char[numApostrophes+origin.length];
00128 int index=0;
00129 for (int f=0;f<origin.length; f++) {
00130 if (origin[f]=='\'') {
00131 parsed[index++]=origin[f];
00132 };
00133 parsed[index++]=origin[f];
00134 }
00135 field = new String(parsed);
00136 }
00137 return "'"+field+"'";
00138 }
00139
00143 public String quote (String s) throws SQLException {
00144
00145 if (s == null) return null;
00146
00147
00148 return "'" + s.replaceAll("'","''") + "'";
00149 }
00150
00154 public String getString (String sql) throws Exception { return ""+getObject(sql); }
00155
00159 public int getInt (String sql) throws Exception { return Integer.valueOf(getString(sql)).intValue(); }
00160
00164 public double getDouble (String sql) throws Exception { return Double.valueOf(getString(sql)).doubleValue(); }
00165
00169 public long getLong (String sql) throws Exception { return Long.valueOf(getString(sql)).longValue(); }
00170
00174 public Object getObject (String sql) throws Exception {
00175 ResultSet r = query(sql);
00176 if (! r.first()) {
00177 r.getStatement().close();
00178 throw new Exception("ResultSet does not contain at least 1 row.\n"+sql);
00179 }
00180 Object o = r.getObject(1);
00181 r.getStatement().close();
00182 return o;
00183 }
00184
00190 public ResultSet query (String sql) throws Exception {
00191 if (connection == null) { throw new Exception("No connection has been set"); }
00192
00193 Statement statement = null;
00194 try {
00195 statement = connection.createStatement();
00196
00197
00198
00199 statement.execute(sql);
00200
00201
00202 ResultSet result = statement.getResultSet();
00203 if (result != null) {
00204 return result;
00205 }
00206
00207
00208 while (statement.getMoreResults()) {
00209 result = statement.getResultSet();
00210 if (result != null) {
00211 return result;
00212 }
00213 }
00214
00215
00216 statement.close();
00217 throw new Exception("A non-null result set could not be found.");
00218
00219 } catch (Exception e) {
00220 throw new Exception("Error occured while executing sql:\n"+sql+"\n"+e.getMessage(),e);
00221 }
00222 }
00223
00227 public void update (String sql) throws Exception {
00228 if (connection == null) { throw new Exception("No connection has been set"); }
00229 Statement statement = null;
00230 try {
00231 statement = connection.createStatement();
00232 statement.executeUpdate(sql);
00233 }
00234 catch (Exception e) {
00235 throw new Exception("Error occured while executing sql:\n"+sql+"\n"+e.getMessage(),e);
00236 }
00237 finally {
00238 try { if (statement != null) { statement.close(); } } catch (Exception e) { e.printStackTrace(); }
00239 }
00240 }
00241
00245 public Statement createStatement() throws Exception {
00246 if (connection == null) { throw new Exception("No connection has been set"); }
00247 return connection.createStatement();
00248 }
00249
00257 public String inClause (Collection c, boolean quoted) throws Exception {
00258 if (c == null || c.size() == 0) { return "(null)"; }
00259 StringBuffer sb = new StringBuffer();
00260 sb.append("(");
00261 for (Iterator i = c.iterator(); i.hasNext(); ) {
00262 Object item = i.next();
00263 if (item == null) {
00264 sb.append("null");
00265 }
00266 else if (quoted) {
00267 sb.append(quote(item.toString()));
00268 }
00269 else {
00270 sb.append(item.toString());
00271 }
00272 sb.append(",");
00273 }
00274 sb.deleteCharAt( sb.length()-1 );
00275 sb.append(")");
00276 return sb.toString();
00277 }
00278
00282 public int rowCount (ResultSet r) throws Exception {
00283 int rowCount = 0;
00284 r.beforeFirst();
00285 while (r.next()) { rowCount++; }
00286 r.beforeFirst();
00287 return rowCount;
00288 }
00289
00293 public static Map toMap (ResultSet r) throws Exception {
00294 return toMap(r,true);
00295 }
00296
00304 public static Map toMap (ResultSet r, boolean advance) throws Exception {
00305
00306
00307 if (advance) { r.next(); }
00308
00309
00310 if (r.getRow() == 0) {
00311 return new HashMap();
00312 }
00313
00314
00315
00316 Map map = new LinkedHashMap( 32 );
00317 ResultSetMetaData m = r.getMetaData();
00318 int cc = m.getColumnCount();
00319 for ( int i=1; i<=cc; i++ ){
00320 map.put ( m.getColumnName(i) , r.getString(i) );
00321 }
00322 return map;
00323 }
00324
00328 public List toList (ResultSet r) throws Exception {
00329 List list = new ArrayList(32) ;
00330 while (r.next()){
00331 Map map = new HashMap( 32 );
00332 ResultSetMetaData m = r.getMetaData();
00333 int cc = m.getColumnCount();
00334 for ( int i=1; i<=cc; i++ ){
00335 map.put (
00336 m.getColumnName(i)
00337 , r.getString(i) );
00338 }
00339 list.add(map);
00340 }
00341 return list;
00342 }
00343
00345
00347
00348
00349
00350
00351
00352
00353
00354
00355
00356
00357
00358
00359
00360
00361
00362
00363
00365
00366
00367
00368
00369
00370
00371
00372
00373
00374
00375
00376
00377
00378
00379
00380
00381
00382
00383
00384
00385
00386
00387
00388
00389
00390
00391
00392
00393
00394
00395
00396
00397
00398
00399
00400
00401
00402
00403
00404
00405
00406
00407
00408
00409
00410
00411
00412
00413
00414
00415
00416
00417
00418
00419
00420
00421
00422
00423
00424
00425
00426
00427
00428
00429
00430
00431
00432
00433
00434
00435
00436
00437
00438
00439
00440
00441
00442
00443
00444
00445
00446
00447
00448
00449
00450
00451 public StringBuffer resultSetToXML (ResultSet r) throws Exception {
00452 return resultSetToXML(r,new StringBuffer(), Integer.MAX_VALUE);
00453 }
00454
00458 public StringBuffer resultSetToXML (ResultSet r, StringBuffer sb, int count) throws Exception {
00459
00460 String emptyString = "";
00461
00462 if (r == null) { throw new Exception("No ResultSet provided."); }
00463 if (sb == null) { throw new Exception("No StringBuffer provided."); }
00464 if (count < 0) { throw new Exception("Count must be positive (" + count + ")"); }
00465
00466 int columnCount = r.getMetaData().getColumnCount();
00467 String[] columnNames = new String[ columnCount ];
00468 for (int i=1; i <= columnCount; i++) {
00469 columnNames[i-1] = r.getMetaData().getColumnName(i);
00470 }
00471
00472 sb.append("<resultSet>\n");
00473 for (int x = 0; x < count && r.next(); x++) {
00474 sb.append("<row>\n");
00475
00476 for (int i=1; i <= columnCount; i++) {
00477 Object value = r.getObject(i);
00478 if (value == null) { value = emptyString; }
00479 sb.append("\t<"); sb.append(columnNames[i-1]); sb.append(">");
00480 sb.append( (""+r.getObject(i)).replaceAll("&","&" ));
00481 sb.append("</"); sb.append(columnNames[i-1]); sb.append(">\n");
00482 }
00483 sb.append("</row>\n");
00484 }
00485 sb.append("</resultSet>\n");
00486 return sb;
00487 }
00488
00489 public void finalize () {
00490 if (connection != null && connectionIsPrivate) {
00491 try { connection.close(); }
00492 catch (Exception e) {
00493 System.out.println("Error while closing connection during finalization");
00494 e.printStackTrace();
00495 }
00496 }
00497 }
00498 }