poolmanstatement.java

来自「Java Database connection pool」· Java 代码 · 共 371 行

JAVA
371
字号
/* *  PoolMan Java Object Pooling and Caching Library *  Copyright (C) 1999-2001 The Code Studio * *  This library is free software; you can redistribute it and/or *  modify it under the terms of the GNU Lesser General Public *  License as published by the Free Software Foundation; either *  version 2 of the License, or (at your option) any later version. * *  This library is distributed in the hope that it will be useful, *  but WITHOUT ANY WARRANTY; without even the implied warranty of *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU *  Lesser General Public License for more details. * *  The full license is located at the root of this distribution *  in the LICENSE file. */package com.codestudio.sql;// Code Studio Libraryimport com.codestudio.util.JDBCPool;import com.codestudio.util.ObjectPool;import com.codestudio.util.PooledObject;import com.codestudio.util.SQLCache;import java.sql.*;import java.util.ArrayList;import java.util.Iterator;import java.util.StringTokenizer;import java.util.WeakHashMap;/** * A SQL Statement that is aware of its Connection and resources. *<p> * It encapsulates a true driver-specific Statement that handles * all the necessary JDBC methods by delegation. */public class PoolManStatement implements Statement, PooledObject {    private Statement statement;    protected String sqlString;    protected ResultSet lastRS;    protected WeakHashMap openres;    protected JDBCPool mypool;    protected PoolManConnection poolmanCon;    protected boolean closed = false;    protected int resultSetType = ResultSet.TYPE_FORWARD_ONLY;    protected int resultSetConcurrency = ResultSet.CONCUR_READ_ONLY;    public PoolManStatement(PoolManConnection pcon, Statement s, ObjectPool p) {        this.poolmanCon = pcon;        this.statement = s;        this.mypool = (JDBCPool) p;        this.openres = new WeakHashMap();    }    public Statement getNativeStatement() {        return this.statement;    }    public void setResultSetType(int i) {        this.resultSetType = i;    }    public void setResultSetConcurrency(int i) {        this.resultSetConcurrency = i;    }    public void closeAllResources() {        try {            this.statement.close();        } catch (SQLException sqle) {        }    }    /** Close any lingering ResultSets. */    public void clean() {        for (Iterator iter = openres.keySet().iterator(); iter.hasNext();) {            JDBCPool.closeResultSet((ResultSet) iter.next());        }        //openres = new WeakHashMap();    }    public void removeOpenResultSet(ResultSet rs) {        if (openres.containsKey(rs))            openres.remove(rs);    }    public ObjectPool getPool() {        return this.mypool;    }    public Connection getConnection() throws SQLException {        return mypool.requestConnection();    }    public String getSQL() {        return this.sqlString;    }    public ResultSet executeQuery(String sql) throws SQLException {        this.sqlString = sql;        ArrayList rowlist = new ArrayList();        ResultSet r = null;        // determine if the results are already cached        // (note that native ResultSets are not cached)        if (mypool.usingCache()) {            PoolManResultSet results = null;            SQLCache jc = mypool.getCache();            try {                results = (PoolManResultSet) jc.getResult(sql);            } catch (Exception cee) {            }            if (results != null) {                mypool.debug("Statement: Returning cached result");                // set correct options                results.setScrollableType(this.resultSetType);                results.setConcurrencyType(this.resultSetConcurrency);                openres.put(results, null);                lastRS = results;                return results;            }        }        // determine whether we need a PoolMan ResultSet Impl        r = this.statement.executeQuery(sql);        if (mypool.isUsingNativeResults()) {            openres.put(r, null);            lastRS = r;            return r;        }        ResultSetMetaData rmeta = PoolManResultSetMetaData.getCopy(r.getMetaData());        try {            int cols = rmeta.getColumnCount();            String[] tableNames = new String[cols];            for (int i = 0; i < cols; i++) {                // Some irritating drivers don't supply a  table name!!                String tableName = null;                try {                    tableName = rmeta.getTableName(i);                    if (tableName.trim().length() == 0)                        tableName = null;                } catch (Exception e) {                    tableName = null;                }                // try to fabricate it if this happens to be one of those drivers.                if (tableName == null)                    tableName = fabricateTableName(sql, i);                tableNames[i] = tableName;            }            while (r.next()) {                ArrayList row = new ArrayList();                for (int i = 1; i <= cols; i++) {                    Result data = new Result(tableNames[i - 1], rmeta.getColumnLabel(i), r.getObject(i),                                             rmeta.getColumnType(i));                    row.add(data);                }                rowlist.add(row);            }        } catch (Exception e) {            mypool.debug("Exception while attempting a SQL operation", e);            throw new SQLException(e.getMessage());        }        finally {            if (null != r) {                try {                    r.close();                } catch (Exception ee) {                }            }        }        PoolManResultSet finalRes = new PoolManResultSet(this, rowlist, rmeta, this.resultSetType, this.resultSetConcurrency);        openres.put(finalRes, null);        lastRS = finalRes;        // cache it if necessary        if ((mypool.usingCache()) && (rowlist.size() > 0)) {            SQLCache jc = mypool.getCache();            jc.cacheResult(sql, finalRes);        }        return finalRes;    }    public String fabricateTableName(String sql, int index) {        String tableName = null;        try {            sql = sql.trim().toLowerCase();            String fromPart = sql.substring(sql.indexOf("from"));            if (fromPart.indexOf("where") != -1)                fromPart = fromPart.substring(0, fromPart.indexOf("where"));            fromPart = fromPart.substring(4).trim();            if (fromPart.indexOf(",") == -1) {                tableName = fromPart;            }            else {                String selectPart = sql.substring(sql.indexOf("select"));                if (selectPart.indexOf("from") != -1)                    selectPart = selectPart.substring(0, selectPart.indexOf("from"));                selectPart = selectPart.substring(6).trim();                StringTokenizer stt = new StringTokenizer(selectPart, ",");                int count = 1;                if (stt.hasMoreTokens()) {                    while (count < index) {                        stt.nextToken();                        count++;                    }                    String tok = stt.nextToken();                    tableName = tok.substring(0, tok.indexOf('.')).trim();                }            }        } catch (Exception e) {        }        return tableName;    }    public int executeUpdate(String sql) throws SQLException {        this.sqlString = sql;        return this.statement.executeUpdate(sql);    }    public void close() throws SQLException {        clean();        this.statement.close();        poolmanCon.removeOpenStatement(this);        this.closed = true;    }    public boolean isClosed() {        return closed;    }    public int getMaxFieldSize() throws SQLException {        return this.statement.getMaxFieldSize();    }    public void setMaxFieldSize(int max) throws SQLException {        this.statement.setMaxFieldSize(max);    }    public int getMaxRows() throws SQLException {        return this.statement.getMaxRows();    }    public void setMaxRows(int max) throws SQLException {        this.statement.setMaxRows(max);    }    public void setEscapeProcessing(boolean enable) throws SQLException {        this.statement.setEscapeProcessing(enable);    }    public int getQueryTimeout() throws SQLException {        return this.statement.getQueryTimeout();    }    public void setQueryTimeout(int seconds) throws SQLException {        this.statement.setQueryTimeout(seconds);    }    public void cancel() throws SQLException {        this.statement.cancel();    }    public SQLWarning getWarnings() throws SQLException {        return this.statement.getWarnings();    }    public void clearWarnings() throws SQLException {        this.statement.clearWarnings();    }    public void setCursorName(String name) throws SQLException {        this.statement.setCursorName(name);    }    public boolean execute(String sql) throws SQLException {        this.sqlString = sql.toLowerCase();        if (sqlString.indexOf("select") != -1) {            executeQuery(sql);            return true;        }        return this.statement.execute(sql);    }    public ResultSet getResultSet() throws SQLException {        if (lastRS != null)            return lastRS;        return this.statement.getResultSet();    }    public int getUpdateCount() throws SQLException {        return this.statement.getUpdateCount();    }    public boolean getMoreResults() throws SQLException {        return this.statement.getMoreResults();    }    public void setFetchDirection(int direction) throws SQLException {        this.statement.setFetchDirection(direction);    }    public int getFetchDirection() throws SQLException {        return this.statement.getFetchDirection();    }    public void setFetchSize(int rows) throws SQLException {        this.statement.setFetchSize(rows);    }    public int getFetchSize() throws SQLException {        return this.statement.getFetchSize();    }    public int getResultSetConcurrency() throws SQLException {        return this.resultSetConcurrency;    }    public int getResultSetType() throws SQLException {        return this.resultSetType;    }    public void addBatch(String sql) throws SQLException {        this.statement.addBatch(sql);    }    public void clearBatch() throws SQLException {        this.statement.clearBatch();    }    public int[] executeBatch() throws SQLException {        return this.statement.executeBatch();    }
    /* OBJECT METHODS */

    public String toString() {        return "PoolManStatement-[UnderlyingStatement:" + this.statement.toString() + "]";    }}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?