1 16 package scriptella.jdbc; 17 18 import scriptella.spi.ParametersCallback; 19 import scriptella.util.ColumnsMap; 20 import scriptella.util.IOUtils; 21 22 import java.io.Closeable ; 23 import java.sql.ResultSet ; 24 import java.sql.ResultSetMetaData ; 25 import java.sql.SQLException ; 26 27 28 35 public class ResultSetAdapter implements ParametersCallback, Closeable { 36 37 private ResultSet resultSet; 38 private ColumnsMap columnsMap; 39 private ParametersCallback params; private JdbcTypesConverter converter; 41 private int columnsCount; 42 private int[] jdbcTypes; 43 44 51 public ResultSetAdapter(ResultSet resultSet, 52 ParametersCallback parametersCallback, JdbcTypesConverter converter) { 53 this.params = parametersCallback; 54 this.resultSet = resultSet; 55 this.converter = converter; 56 } 57 58 private void initMetaData() { 59 columnsMap = new ColumnsMap(); 60 try { 61 final ResultSetMetaData m = resultSet.getMetaData(); 62 columnsCount = m.getColumnCount(); 63 jdbcTypes = new int[columnsCount]; 64 for (int i = 1; i <= columnsCount; i++) { 65 columnsMap.registerColumn(m.getColumnName(i), i); 66 jdbcTypes[i-1]=m.getColumnType(i); } 68 } catch (SQLException e) { 69 throw new JdbcException("Unable to process result set ", e); 70 } 71 } 72 73 77 public boolean next() { 78 try { 79 return resultSet.next(); 80 } catch (SQLException e) { 81 throw new JdbcException("Unable to move cursor to the next row", e); 82 } 83 } 84 85 86 public Object getParameter(final String name) { 87 if (columnsMap==null) { initMetaData(); 89 } 90 try { 91 Integer index = columnsMap.find(name); 92 int ind = index==null?-1:index - 1; 93 if (ind >= 0 && ind < columnsCount) { return converter.getObject(resultSet, ind + 1, jdbcTypes[ind]); 95 } else { return params.getParameter(name); 97 } 98 99 } catch (SQLException e) { 100 throw new JdbcException("Unable to get parameter " + name, e); 101 } 102 } 103 104 108 public void close() { 109 if (resultSet != null) { 110 JdbcUtils.closeSilent(resultSet); 111 IOUtils.closeSilently(converter); 112 resultSet = null; 113 params = null; 114 columnsMap = null; 115 jdbcTypes=null; 116 } 117 } 118 } 119 | Popular Tags |