1 25 26 package org.snipsnap.jdbc; 27 28 import org.snipsnap.util.ConnectionManager; 29 30 import javax.sql.DataSource ; 31 import java.sql.Connection ; 32 import java.sql.PreparedStatement ; 33 import java.sql.ResultSet ; 34 import java.sql.SQLException ; 35 36 42 43 public class JDBCTemplate { 44 private DataSource ds; 45 private PreparedStatementSetter setter; 46 47 public JDBCTemplate(DataSource ds) { 48 this.ds = ds; 49 } 50 51 public void query(String query, RowCallbackHandler handler, PreparedStatementSetter setter) { 52 this.setter = setter; 53 query(query, handler); 54 } 55 56 public int update(String query) { 57 PreparedStatement statement = null; 58 ResultSet result = null; 59 Connection connection = null; 60 int count = -1; 61 62 try { 63 connection = ds.getConnection(); 64 statement = connection.prepareStatement(query); 65 if (null != setter) { 66 setter.setValues(statement); 67 } 68 count = statement.executeUpdate(); 69 } catch (SQLException e) { 71 throw new RuntimeException ("JDBCTemplate: unable to execute query", e); 72 } finally { 73 ConnectionManager.close(result); 74 ConnectionManager.close(statement); 75 ConnectionManager.close(connection); 76 } 77 return count; 78 } 79 80 public int update(String query, PreparedStatementSetter setter) { 81 this.setter = setter; 82 return update(query); 83 } 84 85 public void query(String query, RowCallbackHandler handler) { 86 PreparedStatement statement = null; 87 ResultSet result = null; 88 Connection connection = null; 89 90 try { 91 connection = ds.getConnection(); 92 statement = connection.prepareStatement(query); 93 if (null != setter) { 94 setter.setValues(statement); 95 } 96 97 result = statement.executeQuery(); 98 while (result.next()) { 99 handler.processRow(result); 100 } 101 102 } catch (SQLException e) { 103 throw new RuntimeException ("JDBCTemplate: unable to execute query", e); 104 } finally { 105 ConnectionManager.close(result); 106 ConnectionManager.close(statement); 107 ConnectionManager.close(connection); 108 } 109 110 } 111 } 112 | Popular Tags |