1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.commons.dbutils;
18
19 import java.sql.ResultSet;
20 import java.sql.SQLException;
21 import java.util.Iterator;
22
23 /**
24 * <p>
25 * Wraps a <code>ResultSet</code> in an <code>Iterator</code>. This is useful
26 * when you want to present a non-database application layer with domain
27 * neutral data.
28 * </p>
29 *
30 * <p>
31 * This implementation requires the <code>ResultSet.isLast()</code> method
32 * to be implemented.
33 * </p>
34 */
35 public class ResultSetIterator implements Iterator {
36
37 /**
38 * The wrapped <code>ResultSet</code>.
39 */
40 private ResultSet rs = null;
41
42 /**
43 * The processor to use when converting a row into an Object[].
44 */
45 private RowProcessor convert = new BasicRowProcessor();
46
47 /**
48 * Constructor for ResultSetIterator.
49 * @param rs Wrap this <code>ResultSet</code> in an <code>Iterator</code>.
50 */
51 public ResultSetIterator(ResultSet rs) {
52 this.rs = rs;
53 }
54
55 /**
56 * Constructor for ResultSetIterator.
57 * @param rs Wrap this <code>ResultSet</code> in an <code>Iterator</code>.
58 * @param convert The processor to use when converting a row into an
59 * <code>Object[]</code>. Defaults to a
60 * <code>BasicRowProcessor</code>.
61 */
62 public ResultSetIterator(ResultSet rs, RowProcessor convert) {
63 this.rs = rs;
64 this.convert = convert;
65 }
66
67 /**
68 * Returns true if there are more rows in the ResultSet.
69 * @return boolean <code>true</code> if there are more rows
70 * @throws RuntimeException if an SQLException occurs.
71 */
72 public boolean hasNext() {
73 try {
74 return !rs.isLast();
75 } catch (SQLException e) {
76 rethrow(e);
77 return false;
78 }
79 }
80
81 /**
82 * Returns the next row as an <code>Object[]</code>.
83 * @return An <code>Object[]</code> with the same number of elements as
84 * columns in the <code>ResultSet</code>.
85 * @see java.util.Iterator#next()
86 * @throws RuntimeException if an SQLException occurs.
87 */
88 public Object next() {
89 try {
90 rs.next();
91 return this.convert.toArray(rs);
92 } catch (SQLException e) {
93 rethrow(e);
94 return null;
95 }
96 }
97
98 /**
99 * Deletes the current row from the <code>ResultSet</code>.
100 * @see java.util.Iterator#remove()
101 * @throws RuntimeException if an SQLException occurs.
102 */
103 public void remove() {
104 try {
105 this.rs.deleteRow();
106 } catch (SQLException e) {
107 rethrow(e);
108 }
109 }
110
111 /**
112 * Rethrow the SQLException as a RuntimeException. This implementation
113 * creates a new RuntimeException with the SQLException's error message.
114 * @param e SQLException to rethrow
115 * @since DbUtils 1.1
116 */
117 protected void rethrow(SQLException e) {
118 throw new RuntimeException(e.getMessage());
119 }
120
121 }