pingpong.db.DBAccess.java Source code

Java tutorial

Introduction

Here is the source code for pingpong.db.DBAccess.java

Source

/*
 * Copyright (C) The ThinkTier Software. All rights reserved. This software is published under the terms of the ThinkTier Software
 * License. Created on 2004. 7. 6.
 */
package pingpong.db;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.Hashtable;
import java.util.ResourceBundle;

import javax.naming.InitialContext;
import javax.sql.DataSource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import pingpong.db.sql.TStatement;
import pingpong.util.StringUtil;

/**
 * <p>
 * Title: DBAccess
 * </p>
 * <p>
 * Description: DataBase?  ? ?
 * </p>
 * 
 * TimeOut
 * url="jdbc:as400://my.400.com;libraries=LIB1,LIB2,LIB3;socket timeout=30000;thread used=false"
 * http://doctorjw.wordpress.com/2010/05/18/jdbc-and-the-jt400-jar/
 * 
 * @author <a href="mailto:tglim@korea.com">TaekGu Lim</a>
 * @since Pingpong 1.0
 * @version 1.0
 */

public class DBAccess {

    private DataSource ds = null;

    // private static boolean tracing = false; // Debug 
    private static final Log log = LogFactory.getLog(DBAccess.class);

    private static final String RESOURCE_BUNDLE = "pingpong.db.db";//$NON-NLS-1$

    private static String class_path = null;

    private Connection m_con;

    private static Hashtable<String, String> dbNames = new Hashtable<String, String>();

    private static Hashtable<String, DataSource> dsHash = new Hashtable<String, DataSource>();

    private String dbName;

    private boolean usedDataSource = true;

    private int state;

    private String sqlState;

    private String message;

    public DBAccess() {
        try {
            this.dbName = DBAccess.getDefaultDataBase().toUpperCase();
            initDataBase(dbName);
        } catch (IOException e) {
            log.error("DefaultDataBase ?? .");
        }
    }

    public DBAccess(final String dbName) {
        this.dbName = dbName.toUpperCase();
        initDataBase(this.dbName);
    }

    public DBAccess(final String dbName, boolean usedDataSource) {
        this.dbName = dbName;
        this.usedDataSource = usedDataSource;
        initDataBase(dbName);
    }

    /**
     * WAS?? ? DataSource  .
     * @throws SQLException 
     */
    private void getDS() throws SQLException {
        if (ds != null)
            return;
        try {
            InitialContext ctx = new InitialContext();
            ds = (DataSource) ctx.lookup("java:comp/env/" + getLookup());
            /*
            BasicDataSource ds1 = null;
            if( ds != null ){
            ds1 = (BasicDataSource) ds;
               StringBuffer buf = new StringBuffer();
               buf.append(ds1.getUrl());
               buf.append("GETB:MaxActive:" + ds1.getMaxActive())
                  .append("\tMaxIdle:" + ds1.getMaxIdle())
                  .append("\tNumActive:" + ds1.getNumActive())
                  .append("\tNumIdle:" + ds1.getNumIdle());
               log.debug(buf.toString());
            }
            */
        } catch (Exception e) {
            ds = null;
            if (usedDataSource) {
                //log.error("Naming service exception: " + e.getMessage());
                log.error("get DataSource fail : " + "java:comp/env/" + getLookup());
                //e.printStackTrace();
            }
            ds = setupDataSource();
        }
    }

    private DataSource setupDataSource() throws SQLException {
        DataSource ds = null;
        if (DBAccess.dsHash.containsKey(dbName)) {
            ds = DBAccess.dsHash.get(dbName);
        } else {
            log.error("Setting DataSource Failure");
            //           log.debug("Setting up data source.");
            //            BasicDataSource ds1 = new BasicDataSource();
            //            ds1.setDriverClassName(getDriver());
            //            ds1.setUsername(getUserName());
            //            ds1.setPassword(getPassword());
            //            ds1.setUrl(getUrl());
            //            DBAccess.dsHash.put(dbName, ds1);
            //            ds = ds1;
            //            log.debug("Done.");
        }
        DBAccess.printDataSourceStats(ds);
        return ds;
    }

    public static void printDataSourceStats(DataSource ds) throws SQLException {
        //        BasicDataSource ds1 = (BasicDataSource) ds;
        //      StringBuffer buf = new StringBuffer();
        //      buf.append("MaxActive:" + ds1.getMaxActive())
        //         .append("\tMaxIdle:" + ds1.getMaxIdle())
        //         .append("\tNumActive:" + ds1.getNumActive())
        //         .append("\tNumIdle:" + ds1.getNumIdle())
        //         .append("\t" + ds1.getUrl());
        //      log.debug(buf.toString());
    }

    private String getLookup() {
        ResourceBundle rb;
        try {
            rb = getResourceBundle();
            state = 0;
        } catch (Exception e) {
            state = 1;
            return "";
        }
        return StringUtil.nvl(rb.getString(dbName + ".lookup"), "");
    }

    /**
     *  DB? schema 
     * 
     * @return  DB? schema 
     */
    public String getSchema() {
        // Properties p;
        ResourceBundle rb;
        try {
            // p = getDBProperties();
            rb = getResourceBundle();
            state = 0;
        } catch (Exception e) {
            state = 1;
            return "";
        }
        return StringUtil.nvl(rb.getString(dbName + ".schema"), rb.getString(dbName + ".username"));
    }

    public String getUrl() {
        ResourceBundle rb;
        try {
            rb = getResourceBundle();
            state = 0;
        } catch (Exception e) {
            state = 1;
            return "";
        }
        return StringUtil.nvl(rb.getString(dbName + ".url"), "");
    }

    public String getUserName() {
        ResourceBundle rb;
        try {
            rb = getResourceBundle();
            state = 0;
        } catch (Exception e) {
            state = 1;
            return "";
        }
        return StringUtil.nvl(rb.getString(dbName + ".username"), "");
    }

    public String getDriver() {
        ResourceBundle rb;
        try {
            rb = getResourceBundle();
            state = 0;
        } catch (Exception e) {
            state = 1;
            return "";
        }
        return StringUtil.nvl(rb.getString(dbName + ".driver"), "");
    }

    public String getPassword() {
        ResourceBundle rb;
        try {
            rb = getResourceBundle();
            state = 0;
        } catch (Exception e) {
            state = 1;
            return "";
        }
        return StringUtil.nvl(rb.getString(dbName + ".password"), "");
    }

    /**
     * "db.properties"? ?? DBMS? ?? 
     * 
     * @return "db.properties"? ?? DBMS? ?? 
     */
    public static String[] getDBMS() {
        try {
            ResourceBundle rb = getResourceBundle();
            String names[] = rb.getString("dbms").split(",");
            for (int i = 0; i < names.length; i++) {
                names[i] = names[i].trim();
            }
            return names;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * DataBase  ? .
     * 
     * @return
     */
    private static ResourceBundle getResourceBundle() {
        String env = System.getProperty("server.info");

        if (env == null || env.equals("")) {
            env = "local";
        }

        ResourceBundle rb = ResourceBundle.getBundle(RESOURCE_BUNDLE + "-" + env);

        return rb;
    }

    /**
     *  DB?  db.properties ? 
     * 
     * @param dbName
     */
    private static void initDataBase(final String dbName) {
        log.debug("dbName:" + dbName);

        if (!dbNames.containsKey(dbName)) {
            try {
                // JDBC Driver Load
                // WAS? ?

                ResourceBundle rb = getResourceBundle();
                Class.forName(StringUtil.nvl(rb.getString(dbName + ".driver"), ""));
                dbNames.put(dbName, dbName);

            } catch (Exception e) {
                e.printStackTrace();
                log.error("DataBase ?:" + e.getMessage());
            }
        }
    }

    /**
     * Connection ? . ? ? ?   Method? ? . <BR>
     * <ul>
     * <li> ?    </li>
     * <li>CallableStatement   </li>
     * <li>     </li>
     * </ul>
     * <br>
     * ? <CODE>DBAccess</CODE> ??    ?.  ? ?    SQLException? ?. <rb><BR>
     * <FONT COLOR="#FF0000">    Connection?  ?? ?  close()  Connection?  . </FONT>
     * 
     * @return Connection
     * @throws SQLException
     */
    public Connection getConnection() throws SQLException {
        Connection conn = null;
        //      BasicDataSource ds1 = null;
        //  Connection?  
        if (m_con == null) {
            //  WAS?  DataSource .
            if (ds == null)
                getDS();
            if (ds != null) {
                conn = ds.getConnection();
                //            ds1 = (BasicDataSource) ds;
                //            StringBuffer buf = new StringBuffer();
                //            buf.append(ds1.getUrl());
                //            buf.append("GETA:MaxActive:" + ds1.getMaxActive())
                //               .append("\tMaxIdle:" + ds1.getMaxIdle())
                //               .append("\tNumActive:" + ds1.getNumActive())
                //               .append("\tNumIdle:" + ds1.getNumIdle());
                //            log.debug(buf.toString());
            } else {
                conn = DriverManager.getConnection(getUrl(), getUserName(), getPassword());
            }
            conn.setAutoCommit(true);
        } else {
            conn = m_con;
        }
        return conn;
    }

    /**
     *  ? . <br>
     * ? ? ???  ? . <BR>
     * <FONT COLOR="#FF0000">begin()  ?  commit()? rollback()  . </FONT>
     * 
     * @exception SQLException
     *                 ? ? 
     * @see #commit
     * @see #rollback
     * @see #end
     */
    public void begin() throws SQLException {
        m_con = getConnection();
        if (m_con.getAutoCommit()) {
            m_con.setAutoCommit(false);
        }
    }

    /**
     * Transaction?   connection? .
     * ?  connection? .
     * <FONT COLOR="#FF0000"> end()  . </FONT>
     * @throws SQLException
     */
    public void beginOne() throws SQLException {
        m_con = getConnection();
    }

    /**
     * begin()  ?  Connection? . <BR>
     *  begin()? ?  commit()? rollback()?    end()  ? ?? Rollback?. <br>
     * <FONT COLOR="#FF0000">begin()  ?  end()  . </FONT>
     * 
     * @see #begin
     */
    public void end() {
        try {
            rollback();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * begin()  ? Commit.
     * 
     * @exception SQLException
     *                 ? ? 
     * @see #begin
     * @see #rollback
     * @see #end
     */
    public void commit() throws SQLException {
        if (m_con != null)
            m_con.commit();
    }

    /**
     * begin()  ? Rollback.
     * 
     * @exception SQLException
     *                 ? ? 
     * @see #begin
     * @see #commit
     * @see #end
     */
    public void rollback() throws SQLException {
        if (m_con != null) {
            if (!m_con.getAutoCommit())
                m_con.rollback();
        }
    }

    /**
     * getConnection()? ? Connection?  ?. <br>
     * <FONT COLOR="#FF0000"> getConnection()  Connection    ?  . </FONT>
     * 
     * @see #getConnection
     */
    public void close() throws SQLException {
        if (m_con != null) {
            m_con.setAutoCommit(true);
            m_con.close();
            m_con = null;
        }
    }

    /**
     * string? scalar? 
     * @param sql
     * @return
     */
    public String getScalarString(String sql) {
        return getScalarString(sql, null);
    }

    /**
     * string? scalar? 
     * @param sql
     * @param args
     * @return
     */
    public String getScalarString(String sql, Object args[]) {
        String value = null;
        try {
            value = getScalar(sql, args).toString();
        } catch (Exception e) {
            value = null;
        }
        return value;
    }

    /**
     * integer? scalar? 
     * null?  0? 
     * @param sql
     * @return
     */
    public int getScalarInt(String sql) {
        return getScalarInt(sql, null);
    }

    /**
     * integer? scalar? 
     * null?  0? 
     * @param sql
     * @param args
     * @return
     */
    public int getScalarInt(String sql, Object args[]) {
        Object value = null;
        try {
            value = getScalar(sql, args);
        } catch (Exception e) {
            value = null;
        }
        return (value == null) ? 0 : Integer.parseInt(value.toString());
    }

    /**
     *  SQL?  ? ? 
     * @param sql
     * @return
     */
    public Object getScalar(String sql) {
        return getScalar(sql, null);
    }

    /**
     *  SQL?  ? ? 
     * @param sql
     * @param args
     * @return
     */
    public Object getScalar(String sql, Object args[]) {
        Object value = null;
        Connection local_con = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try {
            if (m_con != null) {
                pstmt = m_con.prepareStatement(sql);
            } else {
                local_con = getConnection();
                pstmt = local_con.prepareStatement(sql);
            }
            if (args != null) {
                for (int i = 0; i < args.length; i++) {
                    if (args[i] instanceof Null) {
                        pstmt.setNull(i + 1, ((Null) args[i]).type);
                    } else {
                        pstmt.setObject(i + 1, args[i]);
                    }
                }
            }
            rs = pstmt.executeQuery();
            if (rs.next())
                value = rs.getObject(1);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            if (pstmt != null) {
                try {
                    pstmt.close();
                } catch (SQLException e) {
                }
            }
            if (local_con != null) {
                try {
                    local_con.close();
                } catch (SQLException e) {
                }
            }
        }
        return value;
    }

    /**
     * Method executeQuery.
     * 
     * @param sql
     * @return TResultSet
     * @throws SQLException
     * @see #executeQuery(String,Object[],int,int)
     */
    public TResultSet executeQuery(String sql) throws SQLException {

        return executeQuery(sql, null, 0, -1);
    }

    /**
     * Method executeQuery.
     * 
     * @param sql
     * @param skipCount
     * @param getCount
     * @return TResultSet
     * @throws SQLException
     */
    public TResultSet executeQuery(String sql, int skipCount, int getCount) throws SQLException {
        return executeQuery(sql, null, skipCount, getCount);
    }

    /**
     * Method executeQuery.
     * 
     * @param sql
     *             SQL
     * @param args
     *            SQL Statement?   ?
     * @return TResultSet Set
     * @throws SQLExceptions
     * @see #executeQuery(String,Object[],int,int)
     */
    public TResultSet executeQuery(String sql, Object[] args) throws SQLException {
        return executeQuery(sql, args, 0, -1);
    }

    public TResultSet executeQuery(TStatement stmt) throws SQLException {
        return executeQuery(stmt.getRawSQL(), stmt.makeHostValue(), 0, -1);
    }

    /**
     * Method executeQuery.
     * 
     * @param sql
     *             SQL
     * @param args
     *            SQL Statement?   ?
     * @param skipCount
     *            Skip Record
     * @param getCount
     *            Set ? Record
     * @return TResultSet Set
     * @throws SQLException
     */
    public TResultSet executeQuery(String sql, Object[] args, int skipCount, int getCount) throws SQLException {
        Connection local_con = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try {

            log.debug(sql);

            if (m_con != null) {
                pstmt = m_con.prepareStatement(sql);
            } else {
                local_con = getConnection();
                pstmt = local_con.prepareStatement(sql);
            }
            if (args != null) {
                for (int i = 0; i < args.length; i++) {
                    log.debug("arg " + i + " : " + args[i]);
                    if (args[i] instanceof Null) {
                        pstmt.setNull(i + 1, ((Null) args[i]).type);
                    } else {
                        pstmt.setObject(i + 1, args[i]);
                    }
                }

            } else {
                log.debug("arg arg null");
            }

            rs = pstmt.executeQuery();
            state = 0;
            return makeTResultSet(rs, skipCount, getCount);
        } catch (SQLException e) {
            state = e.getErrorCode();
            sqlState = e.getSQLState();
            message = e.getMessage();
            throw e;
        } catch (Exception e) {
            message = e.getMessage();
            e.printStackTrace();
            return null;
        } finally {
            if (rs != null) {
                try {
                    rs.close();
                } catch (Exception e) {
                }
            }
            if (pstmt != null) {
                try {
                    pstmt.close();
                } catch (Exception e) {
                }
            }
            if (local_con != null) {
                try {
                    local_con.close();
                } catch (Exception e) {
                }
            }
        }
    }

    /**
     * ResultSet?  ?  ? .
     * @param sql
     * @param args
     * @return procedure?  rtn_cod, rtn_msg   String[]
     */
    public String[] executeProcedure(String sql, Object args[]) throws SQLException {
        String result[] = { "", "" };
        Connection local_con = null;
        CallableStatement cstmt = null;
        ResultSet rs = null;
        int idxParam = (args == null) ? 0 : args.length;

        log.debug(sql);
        if (args != null) {
            for (int i = 0; i < args.length; i++) {
                log.debug("args" + i + ":" + args[i]);
            }
        }

        try {
            if (m_con != null) {
                cstmt = m_con.prepareCall(sql);
            } else {
                local_con = getConnection();
                cstmt = local_con.prepareCall(sql);
            }
            if (args != null) {

                for (int i = 0; i < args.length; i++) {
                    if (args[i] instanceof Null) {
                        cstmt.setNull(i + 1, ((Null) args[i]).type);
                    } else {
                        cstmt.setObject(i + 1, args[i]);
                    }
                }
            }
            cstmt.setString(idxParam + 1, "");
            cstmt.setString(idxParam + 2, "");
            cstmt.registerOutParameter(idxParam + 1, Types.VARCHAR);
            cstmt.registerOutParameter(idxParam + 2, Types.VARCHAR);
            cstmt.execute();
            result[0] = cstmt.getString(idxParam + 1);
            result[1] = cstmt.getString(idxParam + 2);
        } catch (SQLException e) {
            state = e.getErrorCode();
            sqlState = e.getSQLState();
            message = e.getMessage();
            throw e;
        } catch (Exception e) {
            message = e.getMessage();
            e.printStackTrace();
        } finally {
            if (rs != null) {
                try {
                    rs.close();
                } catch (Exception e) {
                }
            }
            if (cstmt != null) {
                try {
                    cstmt.close();
                } catch (Exception e) {
                }
            }
            if (local_con != null) {
                try {
                    local_con.close();
                } catch (Exception e) {
                }
            }
        }
        return result;
    }

    public TResultSet executeProcedure1(String sql, Object args[]) throws SQLException {
        Connection local_con = null;
        CallableStatement cstmt = null;
        ResultSet rs = null;
        TResultSet ds = null;

        sql = sql.replace(")", ",?)"); //
        log.debug("sql repalce:" + sql + "len:" + args.length);

        int idxParam = (args == null) ? 0 : args.length + 1;
        for (int i = 0; i < args.length; i++)
            log.debug("arg " + i + " : " + args[i]);
        try {
            if (m_con != null) {
                cstmt = m_con.prepareCall(sql);
            } else {
                local_con = getConnection();
                cstmt = local_con.prepareCall(sql);
            }
            if (args != null) {
                for (int i = 0; i < args.length; i++) {
                    //log.debug("###########i: "+i +"/"+args[i]+"/"+args.length);
                    if (args[i] instanceof Null) {
                        cstmt.setNull(i + 1, ((Null) args[i]).type);
                    } else {
                        cstmt.setObject(i + 1, args[i]);
                    }

                }

                // For Oracle Procedure return Cursor
                //            cstmt.registerOutParameter(idxParam, OracleTypes.CURSOR);  //            
            }

            // For Oracle Procedure
            //          cstmt.executeQuery();          
            //          rs = (ResultSet) cstmt.getObject(idxParam);
            rs = cstmt.executeQuery();

            return makeTResultSet(rs, 0, -1);
        } catch (SQLException e) {
            state = e.getErrorCode();
            sqlState = e.getSQLState();
            message = e.getMessage();
            throw e;
        } catch (Exception e) {
            message = e.getMessage();
            e.printStackTrace();
        } finally {
            if (rs != null) {
                try {
                    rs.close();
                } catch (Exception e) {
                }
            }
            if (cstmt != null) {
                try {
                    cstmt.close();
                } catch (Exception e) {
                }
            }
            if (local_con != null) {
                try {
                    local_con.close();
                } catch (Exception e) {
                }
            }
        }
        return ds;
    }

    /**
     * ResultSet?  ?  ? .
     * @param args
     *       -  2? arguments   .
     * @return TResultSet? 
     */
    public TResultSet executeProcedure2(String sql, Object args[]) throws SQLException {
        //      String result[] = {"", ""};
        Connection local_con = null;
        CallableStatement cstmt = null;
        ResultSet rs = null;
        TResultSet ds = null;

        //   sql.replace("?)", "?,?)");
        int idxParam = (args == null) ? 0 : args.length;
        try {
            if (m_con != null) {
                cstmt = m_con.prepareCall(sql);
            } else {
                local_con = getConnection();
                cstmt = local_con.prepareCall(sql);
            }
            if (args != null) {
                for (int i = 0; i < args.length - 2; i++) {
                    if (args[i] instanceof Null) {
                        log.debug("1###########i:" + i + args[i]);

                        cstmt.setNull(i + 1, ((Null) args[i]).type);
                    } else {
                        cstmt.setObject(i + 1, args[i]);
                        log.debug("2###########i:" + i + args[i]);
                    }
                }
                cstmt.setString(idxParam - 1, "");
                cstmt.setString(idxParam, "");
                cstmt.registerOutParameter(idxParam - 1, Types.VARCHAR);
                cstmt.registerOutParameter(idxParam, Types.VARCHAR);
                //   cstmt.registerOutParameter(idxParam, OracleTypes.CURSOR);   
                log.debug("###########sql:" + sql + "\nargs:" + args + " len:" + args.length);
                log.debug("###########sql:" + sql + "\nargs:" + args + " len:" + args.length);
            }
            rs = cstmt.executeQuery();
            ds = new TResultSet(rs);
            args[idxParam - 2] = cstmt.getString(idxParam - 1);
            args[idxParam - 1] = cstmt.getString(idxParam);
        } catch (SQLException e) {
            state = e.getErrorCode();
            sqlState = e.getSQLState();
            message = e.getMessage();
            throw e;
        } catch (Exception e) {
            message = e.getMessage();
            e.printStackTrace();
        } finally {
            if (rs != null) {
                try {
                    rs.close();
                } catch (Exception e) {
                }
            }
            if (cstmt != null) {
                try {
                    cstmt.close();
                } catch (Exception e) {
                }
            }
            if (local_con != null) {
                try {
                    local_con.close();
                } catch (Exception e) {
                }
            }
        }
        return ds;
    }

    public TResultSet executeProcedure3(String sql, Object args[]) throws SQLException {
        Connection local_con = null;
        CallableStatement cstmt = null;
        ResultSet rs = null;
        TResultSet ds = null;

        sql = sql.replace("?)", "?,?)"); //
        log.debug("sql repalce:" + sql);
        int idxParam = (args == null) ? 0 : args.length + 1;
        try {
            if (m_con != null) {
                cstmt = m_con.prepareCall(sql);
            } else {
                local_con = getConnection();
                cstmt = local_con.prepareCall(sql);
            }
            if (args != null) {
                for (int i = 0; i < args.length - 2; i++) {
                    log.debug("###########i: " + i + "/" + args[i] + "/" + args.length);
                    if (args[i] instanceof Null) {
                        cstmt.setNull(i + 1, ((Null) args[i]).type);
                    } else {
                        cstmt.setObject(i + 1, args[i]);
                    }
                }

                cstmt.setString(idxParam - 2, "");
                cstmt.setString(idxParam - 1, "");
                cstmt.registerOutParameter(idxParam - 2, Types.VARCHAR);
                cstmt.registerOutParameter(idxParam - 1, Types.VARCHAR);
                // For Oracle
                //            cstmt.registerOutParameter(idxParam, OracleTypes.CURSOR);  //

                log.debug("###########sql:" + sql + "\nargs:" + args + " len:" + args.length);
            }

            //OracleCallableStatement ? getCursor() method  REF CURSOR 
            //JDBC ResultSet variable ? .         
            //          cstmt.executeQuery();          
            //          rs = (ResultSet) cstmt.getObject(idxParam);
            rs = cstmt.executeQuery();
            ds = new TResultSet(rs);

            args[idxParam - 3] = cstmt.getString(idxParam - 2); //call by refenene  000
            args[idxParam - 2] = cstmt.getString(idxParam - 1); //O.K
            log.debug(cstmt.getString(idxParam - 2) + "," + cstmt.getString(idxParam - 1));
        } catch (SQLException e) {
            state = e.getErrorCode();
            sqlState = e.getSQLState();
            message = e.getMessage();
            throw e;
        } catch (Exception e) {
            message = e.getMessage();
            e.printStackTrace();
        } finally {
            if (rs != null) {
                try {
                    rs.close();
                } catch (Exception e) {
                }
            }
            if (cstmt != null) {
                try {
                    cstmt.close();
                } catch (Exception e) {
                }
            }
            if (local_con != null) {
                try {
                    local_con.close();
                } catch (Exception e) {
                }
            }
        }
        return ds;
    }

    //   
    //   private OracleCallableStatement getOracleCallableStatement(Connection connection, String query)
    //         throws SQLException {
    //      return getOracleCallableStatement(connection.prepareCall(query));
    //   }
    //   
    //   private OracleCallableStatement getOracleCallableStatement(Statement statement) {
    //      if (statement instanceof DelegatingCallableStatement) {
    //         return getOracleCallableStatement(((DelegatingCallableStatement) statement).getDelegate());
    //      }
    //      return (OracleCallableStatement) statement;
    //   }

    /**
     * ResultSet  ? Record 
     * 
     * @param rs
     * @param skipCount
     * @param getCount
     * @return
     * @throws SQLException
     */
    TResultSet makeTResultSet(ResultSet rs, int skipCount, int getCount) throws SQLException {
        /*
         * TResultSet trs = new TResultSet(); trs.setTable(rs, skipCount, getCount); return trs;
         */
        return new TResultSet(rs, skipCount, getCount, isISO8859_1());
    }

    /**
     * TStatement ? ??
     * @param stmt
     * @return
     * @throws SQLException
     */
    public int executeUpdate(TStatement stmt) throws SQLException {
        return executeUpdate(stmt.getRawSQL(), stmt.makeHostValue());
    }

    /**
     *  ?? 
     * 
     * @param sql
     * @return 
     * @throws SQLException
     */
    public int executeUpdate(String sql) throws SQLException {
        return executeUpdate(sql, null);
    }

    /**
     * insert, update, delete .
     * 
     * @param sql
     * @param args
     * @return int
     * @throws SQLException
     */
    public int executeUpdate(String sql, Object[] args) throws SQLException {
        Connection local_con = null;
        PreparedStatement pstmt = null;

        log.debug(sql);
        if (isISO8859_1()) {
            try {
                sql = StringUtil.encodeText(sql);
                if (args != null)
                    for (int i = 0; i < args.length; i++) {
                        log.debug(args[i]);
                        if (args[i] instanceof String) {
                            args[i] = StringUtil.decodeText((String) args[i]);
                        }
                    }
            } catch (UnsupportedEncodingException e) {
            }
        }
        int result = -1;
        try {
            if (m_con != null) {
                pstmt = m_con.prepareStatement(sql);
            } else {
                local_con = getConnection();
                pstmt = local_con.prepareStatement(sql);
            }
            if (args != null) {
                for (int i = 0; i < args.length; i++) {
                    log.debug(args[i]);
                    if (args[i] instanceof Null) {
                        pstmt.setNull(i + 1, ((Null) args[i]).type);
                    } else {
                        pstmt.setObject(i + 1, args[i]);
                    }
                }
            }
            result = pstmt.executeUpdate();
            log.debug("result:" + result);
        } catch (SQLException e) {
            e.printStackTrace();
            StringBuffer sb = new StringBuffer();
            sb.append("Error Message:").append(e.getMessage()).append("\n");
            sb.append("SQL:").append(sql).append("<br>\n");
            if (args != null) {
                sb.append(
                        "<table border=0 cellspacing=1 cellpadding=0 width='100%' class='table_data'><tr><th>index</th><th>argument</th></tr>\n");
                for (int i = 0; i < args.length; i++) {
                    sb.append("<tr class='td_body0" + ((i % 2) + 1) + "'>");
                    sb.append("<td>").append(i).append("</td>");
                    sb.append("<td>").append(args[i]).append("</td>");
                    sb.append("</tr>\n");
                }
                sb.append("</table>\n");
            } else {
                sb.append("args is null");
            }
            SQLException se = new SQLException(sb.toString(), e.getSQLState());
            throw se;
        } finally {
            if (pstmt != null) {
                try {
                    pstmt.close();
                } catch (Exception e) {
                }
            }
            if (local_con != null) {
                try {
                    local_con.close();
                } catch (Exception e) {
                }
            }
        }
        return result;
    }

    /**
     * DataBase? Table? ?.
     * They are ordered by TABLE_TYPE, TABLE_SCHEM and TABLE_NAME
     * @return
     * @throws SQLException
     * @see {@link java.sql.DatabaseMetaData#getTables(String, String, String, String[])}
     */
    public TResultSet getTables(String tableNamePattern, String[] types) throws SQLException {
        Connection con = getConnection();
        DatabaseMetaData dbMeta = con.getMetaData();
        TResultSet rs = new TResultSet(dbMeta.getTables(null, this.getSchema(), tableNamePattern, types));
        //      TResultSet rs = new TResultSet(dbMeta.getTables(null, "SESSION", tableNamePattern, types));
        //      TResultSet rs = new TResultSet(dbMeta.getTableTypes());
        return rs;
    }

    /**
     * @return Returns the class_path.
     */
    public static String getClass_path() {
        return class_path;
    }

    /**
     * @param class_path
     *            The class_path to set.
     */
    public static void setClass_path(String class_path) {
        DBAccess.class_path = class_path;
    }

    /**
     * TableMgr  ???? ? 
     * 
     * @return
     * @throws IOException
     */
    static public String getRepository() throws IOException {
        // Properties p;
        // p = getDBProperties();
        ResourceBundle rb = getResourceBundle();
        String repository = rb.getString("repository");
        return repository;
    }

    /**
     * TableMgr  ???? ? 
     * 
     * @return
     * @throws IOException
     */
    static public String getDefaultDataBase() throws IOException {
        // Properties p;
        // p = getDBProperties();
        ResourceBundle rb = getResourceBundle();
        String repository = rb.getString("defaultDataBase");
        return repository;
    }

    public boolean isISO8859_1() {
        try {
            ResourceBundle rb = getResourceBundle();
            String value = rb.getString(dbName + ".ISO8859_1");
            if (value == null)
                return false;
            else
                return true;
        } catch (Exception ioe) {
            return false;
        }
    }

    /**
     * @return Returns the message.
     */
    public String getMessage() {
        return message;
    }

    /**
     * @return Returns the sqlState.
     */
    public String getSqlState() {
        return sqlState;
    }

    /**
     * @return Returns the state.
     */
    public int getState() {
        return state;
    }

    public TResultSet getProcedure() {
        return getProcedure(null, null);
    }

    public TResultSet getProcedure(String procedureName) {
        return getProcedure(getSchema(), procedureName);
    }

    public TResultSet getProcedure(String schema, String procedureName) {

        Connection con = null;
        DatabaseMetaData dbMeta = null;
        TResultSet rs = null;
        try {
            con = getConnection();
            dbMeta = con.getMetaData();
            rs = new TResultSet(dbMeta.getProcedures(null, getSchema(), null));
        } catch (SQLException e) {
            rs = null;
        }
        return rs;
    }

    private DatabaseMetaData getMetaData() throws SQLException {
        Connection lconn = null;
        lconn = getConnection();
        DatabaseMetaData metaData = lconn.getMetaData();
        return metaData;
    }

    public String getDatabaseProductName() {
        try {
            return getMetaData().getDatabaseProductName();
        } catch (SQLException e) {
            return null;
        }
    }

    public String getDatabaseProductVersion() {
        try {
            return getMetaData().getDatabaseProductVersion();
        } catch (SQLException e) {
            return null;
        }
    }

    public static void main(String[] args) {
        DBAccess db = new DBAccess("Chunji");
        TResultSet ds = null;
        try {
            ds = db.getTables(null, null);
            for (; ds.next();) {
                for (int i = 0; i < ds.getColumnCount(); i++)
                    log.debug(ds.getString(i + 1) + "|");

            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}