01: /*
02: * StatementParameters.java
03: *
04: * This file is part of SQL Workbench/J, http://www.sql-workbench.net
05: *
06: * Copyright 2002-2008, Thomas Kellerer
07: * No part of this code maybe reused without the permission of the author
08: *
09: * To contact the author please send an email to: support@sql-workbench.net
10: *
11: */
12: package workbench.sql.preparedstatement;
13:
14: import java.sql.ParameterMetaData;
15: import java.sql.PreparedStatement;
16: import java.sql.SQLException;
17: import workbench.db.WbConnection;
18: import workbench.log.LogMgr;
19: import workbench.util.SqlUtil;
20:
21: /**
22: * A class to store the parameters for a PreparedStatement
23: * @author support@sql-workbench.net
24: */
25: public class StatementParameters {
26: private int parameterCount;
27: private ParameterDefinition[] parameter;
28:
29: public StatementParameters(String sql, WbConnection conn)
30: throws SQLException {
31: PreparedStatement pstmt = null;
32: try {
33: pstmt = conn.getSqlConnection().prepareStatement(sql);
34: ParameterMetaData meta = pstmt.getParameterMetaData();
35: this .parameterCount = meta.getParameterCount();
36: if (this .parameterCount > 0) {
37: this .parameter = new ParameterDefinition[this .parameterCount];
38:
39: for (int i = 1; i <= this .parameterCount; i++) {
40: int type = meta.getParameterType(i);
41: ParameterDefinition def = new ParameterDefinition(
42: i, type);
43: this .parameter[i - 1] = def;
44: }
45: }
46: } catch (Exception e) {
47: LogMgr.logError("StatementParameter.<init>",
48: "Error when checking parameters", e);
49: if (e instanceof SQLException)
50: throw (SQLException) e;
51: else
52: throw new SQLException(
53: "Error retrieving statement parameters: "
54: + e.getClass().getName());
55: } finally {
56: SqlUtil.closeStatement(pstmt);
57: }
58: }
59:
60: public int getParameterType(int index) {
61: return this .parameter[index].getType();
62: }
63:
64: public Object getParameterValue(int index) {
65: return this .parameter[index].getValue();
66: }
67:
68: public void applyParameter(PreparedStatement pstmt)
69: throws SQLException {
70: for (int i = 0; i < this .parameterCount; i++) {
71: this .parameter[i].setStatementValue(pstmt);
72: }
73: }
74:
75: public boolean isValueValid(int index, String value) {
76: return this .parameter[index].isValueValid(value);
77: }
78:
79: public void setParameterValue(int index, String value) {
80: this .parameter[index].setValue(value);
81: }
82:
83: public int getParameterCount() {
84: return this .parameterCount;
85: }
86:
87: public boolean hasParameter() {
88: return this .parameterCount > 0;
89: }
90: }
|