1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.commons.dbutils.handlers;
18
19 import java.sql.ResultSet;
20 import java.sql.SQLException;
21
22 import org.apache.commons.dbutils.ResultSetHandler;
23
24 /**
25 * <code>ResultSetHandler</code> implementation that converts one
26 * <code>ResultSet</code> column into an Object. This class is thread safe.
27 *
28 * @see org.apache.commons.dbutils.ResultSetHandler
29 */
30 public class ScalarHandler implements ResultSetHandler {
31
32 /**
33 * The column number to retrieve.
34 */
35 private int columnIndex = 1;
36
37 /**
38 * The column name to retrieve. Either columnName or columnIndex
39 * will be used but never both.
40 */
41 private String columnName = null;
42
43 /**
44 * Creates a new instance of ScalarHandler. The first column will
45 * be returned from <code>handle()</code>.
46 */
47 public ScalarHandler() {
48 super();
49 }
50
51 /**
52 * Creates a new instance of ScalarHandler.
53 *
54 * @param columnIndex The index of the column to retrieve from the
55 * <code>ResultSet</code>.
56 */
57 public ScalarHandler(int columnIndex) {
58 this.columnIndex = columnIndex;
59 }
60
61 /**
62 * Creates a new instance of ScalarHandler.
63 *
64 * @param columnName The name of the column to retrieve from the
65 * <code>ResultSet</code>.
66 */
67 public ScalarHandler(String columnName) {
68 this.columnName = columnName;
69 }
70
71 /**
72 * Returns one <code>ResultSet</code> column as an object via the
73 * <code>ResultSet.getObject()</code> method that performs type
74 * conversions.
75 *
76 * @return The column or <code>null</code> if there are no rows in
77 * the <code>ResultSet</code>.
78 *
79 * @throws SQLException if a database access error occurs
80 *
81 * @see org.apache.commons.dbutils.ResultSetHandler#handle(java.sql.ResultSet)
82 */
83 public Object handle(ResultSet rs) throws SQLException {
84
85 if (rs.next()) {
86 if (this.columnName == null) {
87 return rs.getObject(this.columnIndex);
88 } else {
89 return rs.getObject(this.columnName);
90 }
91
92 } else {
93 return null;
94 }
95 }
96 }