01: /*
02: * PreparedStatementPool.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.PreparedStatement;
15: import java.sql.SQLException;
16: import java.util.HashMap;
17: import java.util.Map;
18: import workbench.db.WbConnection;
19: import workbench.util.SqlUtil;
20:
21: /**
22: * A Pool to store parameters for prepared statements
23: *
24: * @author support@sql-workbench.net
25: */
26: public class PreparedStatementPool {
27: // A map to store the statements and their parameter definitions
28: // The key to the map is the SQL Statement, the value is an Object
29: // of type StatementParameter
30: private Map<String, StatementParameters> statements = new HashMap<String, StatementParameters>();
31: private WbConnection dbConnection;
32:
33: public PreparedStatementPool(WbConnection conn) {
34: setConnection(conn);
35: }
36:
37: private void setConnection(WbConnection conn) {
38: this .done();
39: this .dbConnection = conn;
40: }
41:
42: public void done() {
43: this .dbConnection = null;
44: if (this .statements != null)
45: this .statements.clear();
46: }
47:
48: public synchronized StatementParameters getParameters(String sql) {
49: return this .statements.get(sql);
50: }
51:
52: public synchronized boolean addPreparedStatement(String sql)
53: throws SQLException {
54: if (sql == null)
55: return false;
56: if (sql.indexOf('?') == -1)
57: return false;
58:
59: String clean = SqlUtil.makeCleanSql(sql, false, false, '\'');
60: if (clean.indexOf('?') == -1)
61: return false;
62:
63: if (this .statements.containsKey(sql)) {
64: return true;
65: }
66: StatementParameters p = new StatementParameters(sql,
67: this .dbConnection);
68: if (!p.hasParameter()) {
69: return false;
70: }
71: this .statements.put(sql, p);
72: return true;
73: }
74:
75: public PreparedStatement prepareStatement(String sql)
76: throws SQLException {
77: if (this .dbConnection == null)
78: throw new NullPointerException("No SQL Connection!");
79:
80: StatementParameters parm = this .getParameters(sql);
81: if (parm == null)
82: throw new IllegalArgumentException(
83: "SQL Statement has not been registered with pool");
84: PreparedStatement pstmt = this .dbConnection.getSqlConnection()
85: .prepareStatement(sql);
86: parm.applyParameter(pstmt);
87: return pstmt;
88: }
89:
90: public synchronized boolean isRegistered(String sql) {
91: return this.statements.containsKey(sql);
92: }
93: }
|