connection.java

来自「cwbbs 云网论坛源码」· Java 代码 · 共 418 行

JAVA
418
字号
package com.cloudwebsoft.framework.db;import java.sql.*;import javax.naming.Context;import javax.sql.DataSource;import javax.naming.InitialContext;import javax.naming.NamingException;import org.apache.log4j.Logger;import cn.js.fan.web.Global;import cn.js.fan.web.*;public class Connection {        boolean debug = false;    java.sql.Connection con = null;    Statement stmt = null;    PreparedStatement pstmt = null;    ResultSet rs = null;    ResultSetMetaData resultsMeta = null;    int rows = 0;    int columns = 0;    String PoolName = null;    String DBDriver = "";      String ConnStr = "";       Logger logger;    boolean isUsePool = false;    boolean supportTransaction = false;    public String connName;            public Connection(String connname) {        this.connName = connname;        logger = Logger.getLogger(Connection.class.getName());        DBInfo dbi = Global.getDBInfo(connname);        if (dbi == null) {            logger.error("Conn:数据库连接池" + connname + "未找到");            return;        } else {            isUsePool = dbi.isUsePool;            DBDriver = dbi.DBDriver;            ConnStr = dbi.ConnStr;            PoolName = dbi.PoolName;        }        if (isUsePool)            initUsePool();        else            initNotUsePool();                if (!Global.isTransactionSupported)            supportTransaction = false;        else {            try {                                DatabaseMetaData dm = null;                dm = con.getMetaData();                supportTransaction = dm.supportsTransactions();            } catch (SQLException e) {                logger.error("Conn:" + e.getMessage());                e.printStackTrace();            }        }    }        public boolean isSupportTransaction() {        return supportTransaction;    }    public void initNotUsePool() {      try {          Class.forName(DBDriver);      }            catch (java.lang.ClassNotFoundException e) {          logger.error(                  "警告:Class not found exception occur. Message is:");          logger.error(e.getMessage());      }            try {          con = DriverManager.getConnection(ConnStr);                                    }            catch (SQLException e) {          logger.error("SQL Exception occur. Message is:");          logger.error(e.getMessage());      }    }    public void initUsePool() {      try {        Context initCtx = new InitialContext();        Context envCtx = (Context) initCtx.lookup("java:comp/env");        DataSource ds = (DataSource) envCtx.lookup(PoolName);        con = ds.getConnection();                              }            catch (NamingException e) {        logger.error("Connection pool fail. Message is:");        logger.error(e.getMessage());      }      catch (SQLException e) {        logger.error("SQL Exception occur. Message is:");        logger.error(e.getMessage());      }    }        public java.sql.Connection getCon() {        return this.con;    }    public Statement getStatement() {        return this.stmt;    }        public ResultSet executeQuery(String sql) throws SQLException {        if (con == null)            return null;        if (stmt==null)            stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,                                       ResultSet.CONCUR_READ_ONLY);        try {            rs = stmt.executeQuery(sql);        } catch (SQLException e) {            if (debug)                System.out.println("Query:" + sql + "---" + e.getMessage());            throw e;        }        return rs;    }    public void addBatch(String sql) throws SQLException {        if (stmt==null)            stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,                                       ResultSet.CONCUR_READ_ONLY);        stmt.addBatch(sql);    }    public int[] executeBatch()throws SQLException {        return stmt.executeBatch();    }        public int executeUpdate(String sql) throws SQLException {        if (con == null)            return 0;        if (stmt == null)            stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,                                       ResultSet.CONCUR_READ_ONLY);        int rowcount = 0;        try {            rowcount = stmt.executeUpdate(sql);        } catch (SQLException e) {            if (debug) {                System.out.println("Update:" + sql + "--" + e.getMessage());            }            throw e;        }        return rowcount;    }        public int getColumns() {        int columns = 0;        try {            this.resultsMeta = this.rs.getMetaData();            columns = this.resultsMeta.getColumnCount();        } catch (SQLException e) {}        return columns;    }        public int getRows() {        rows = 0;        try {                        rs.last();            rows = rs.getRow();            rs.beforeFirst();        } catch (SQLException e) {            System.out.println("getRows error:" + e.getMessage());        }        return this.rows;    }    protected void finalize() throws Throwable {        super.finalize();        if (rs!=null) {            try {                rs.close();            }            catch (Exception e) {                                System.out.println("Conn finalize1: " + e.getMessage());            }            rs = null;        }        if (stmt != null) {            try {                stmt.close();            } catch (Exception e) {                System.out.println("Conn finalize2: " + e.getMessage());            }            stmt = null;        }                        if (con != null) {            try {                if (!con.isClosed()) {                    con.close();                }            } catch (Exception e) {                System.out.println("Conn finalize: " + e.getMessage());            }            con = null;         }    }        public void close() {         try {            finalize();        } catch (java.lang.Throwable e) {            System.out.println("conn.close error:" + e.getMessage());        }    }        public void beginTrans() throws SQLException {        if (!isSupportTransaction()) {            System.out.println("Transaction is not supported");            return;        }        try {                        con.setAutoCommit(false);        } catch (SQLException ex) {            ex.printStackTrace();            System.out.print("beginTrans Errors");            throw ex;        }    }        public void commit() throws SQLException {        if (!isSupportTransaction())            return;        try {            con.commit();        } catch (SQLException ex) {            ex.printStackTrace();            if (debug)                System.out.print("Commit Errors");            throw ex;        }        finally {            con.setAutoCommit(true);        }    }        public void rollback() {        if (!isSupportTransaction())            return;        try {            con.rollback();            con.setAutoCommit(true);        } catch (SQLException ex) {            ex.printStackTrace();            if (debug)                System.out.print("Rollback Errors");                    }    }    public boolean getAutoCommit() throws SQLException {        boolean result = false;        try {            result = con.getAutoCommit();        } catch (SQLException ex) {            ex.printStackTrace();            System.out.println("getAutoCommit fail" + ex.getMessage());            throw ex;        }        return result;    }    public int getTransactionIsolation() throws SQLException {        int re = 0;        try {            re = con.getTransactionIsolation();        } catch (SQLException e) {            e.printStackTrace();            System.out.println("getTransactionIsolation fail" + e.getMessage());        }        return re;    }    public void setFetchSize(int size) {        try {                        if (pstmt!=null) {                pstmt.setFetchSize(size);                return;            }                        if (stmt==null) {                stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,                                           ResultSet.CONCUR_READ_ONLY);            }            stmt.setFetchSize(size);        } catch (SQLException e) {            System.out.println("setFetchSize fail:" + e.getMessage());        }    }        public void setMaxRows(int maxRows) throws            SQLException {        try {                        if (pstmt!=null) {                pstmt.setMaxRows(maxRows);                return;            }                        if (stmt == null)                stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,                                           ResultSet.CONCUR_READ_ONLY);            stmt.setMaxRows(maxRows);        } catch (Throwable t) {                                                                        System.out.println("conn.setMaxRows:" + t.getMessage());            t.printStackTrace();        }    }        public PreparedStatement prepareStatement(String sql) throws SQLException {        if (pstmt!=null) {            pstmt.close();            pstmt = null;        }        pstmt = con.prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE,                                       ResultSet.CONCUR_READ_ONLY);        return pstmt;    }        public ResultSet executePreQuery() throws SQLException {        try {            rs = pstmt.executeQuery();        }        catch (SQLException e) {            System.out.print("executePreQuery:" + pstmt.toString() + "---" + e.getMessage());            throw e;        }        return rs;    }        public int executePreUpdate() throws SQLException {        int rowcount = 0;        if (con == null)            return 0;        try {            rowcount = pstmt.executeUpdate();        } catch (SQLException e) {            if (debug) {                System.out.println(getClass() + "executePreUpdate:" + pstmt.toString() + "---"  + e.getMessage());            }            throw e;        }        return rowcount;    }    public boolean isClosed() {        if (con==null)            return true;        boolean re = false;        try {            re = con.isClosed();        }        catch (SQLException e) {            System.out.println(getClass() + " isClosed:" + e.getMessage());        }        return re;    }}

⌨️ 快捷键说明

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