java数据库连接池

package com.tsingtao.common;
import java.sql.*;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.ArrayList;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

/**
 *
 * <p>Title:数据库操作类DbOperation </p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2004</p>
 * <p>Company: </p>
 * @author sljiang
 * @version 1.0
 */
public class DB {
    public String jndiName = null;
    public Connection conn = null;
    public PreparedStatement psmt = null;
    public ResultSet rs = null;
    public ResultSetMetaData rsmd = null;

    /**
     *DbOperation(),构造函数,默认非事务模式
     */
    public DB() {
      jndiName = "java:comp/env/sm_mobile_num/jdbcmssql";//jndiName;
         try {
             Context ctx = new InitialContext();
             DataSource ds = (DataSource) ctx.lookup(jndiName);
             conn = ds.getConnection();
           
         } catch (NamingException e) {
             System.out.println(
                     "Can not find JNDI Name, datesource configuration error!");
         } catch (SQLException e) {
             System.out.println("Can not connect to database, please check the path and the username and the password!" + e.getMessage());
         }
    }

    /**
     *
     * @param jndiName String
     */
    public DB(String jndiName) {
        jndiName = "";//jndiName;
        try {
            Context ctx = new InitialContext();
            DataSource ds = (DataSource) ctx.lookup(jndiName);
            conn = ds.getConnection();
          
        } catch (NamingException e) {
            System.out.println(
                    "Can not find JNDI Name, datesource configuration error!");
        } catch (SQLException e) {
            System.out.println("Can not connect to database, please check the path and the username and the password!" + e.getMessage());
        }
    }
    public void BeginTransaction() throws SQLException{
     this.conn.setAutoCommit(false);
    }
    public void EndTransaction() throws SQLException{
     if(!this.conn.getAutoCommit()){
      this.conn.commit();
      this.conn.setAutoCommit(true);
     }else
      throw new SQLException("You can not make transaction under auto-commit mode");
    }
    public void FailRollBack() throws SQLException{
     if(!this.conn.getAutoCommit()){
      this.conn.rollback();
     }else
      throw new SQLException("You can not rollback under auto-commit mode");
    }
    /**
     * 查询会返回多条记录的sql语句
     * @param strSql String
     * @throws SQLException
     * @return ArrayList
     */
    public ArrayList query(String strSql) throws SQLException {
        ArrayList DbOperationList = new ArrayList();
        this.psmt = null;
        this.rs = null;
        this.rsmd = null;
       
        try{
         this.psmt = this.conn.prepareStatement(strSql);
         this.rs = psmt.executeQuery();
         this.rsmd = rs.getMetaData();
        }catch(SQLException e){
         if(this.conn.getAutoCommit())
          this.close();
         throw new SQLException(this.MakeErrMsg(strSql,e));
        }
        int columnCount = this.rsmd.getColumnCount();
        try{
         while (this.rs.next()) {
          
             Hashtable ht = new Hashtable();
             for (int i = 1; i <= columnCount; i++) {
                 Object obj = this.rs.getObject(i);
                 if (obj != null){
                    String temp= obj.toString().trim();
                    ht.put(this.rsmd.getColumnName(i),temp);
                 }else{
                     String nuller = "";
                     ht.put(this.rsmd.getColumnName(i),nuller);
                 }
             }
             DbOperationList.add(ht);
         }
        }catch(SQLException e){
            this.rs.close();
            this.psmt.close();
            if(this.conn.getAutoCommit())
             this.close();
         throw e;
        }
        this.rs.close();
        this.psmt.close();
        return DbOperationList;
    }
    /**
     * 查询会返回单条记录的sql语句,例如求最值
     * @param strSql String
     * @throws SQLException
     * @return Hashtable
     */
    public Hashtable queryOne(String strSql) throws SQLException {
        Hashtable ht = new Hashtable();
        this.psmt = null;
        this.rs = null;
        this.rsmd = null;
        try{
         this.psmt = this.conn.prepareStatement(strSql);
         this.rs = this.psmt.executeQuery();
         this.rsmd = this.rs.getMetaData();
        }catch(SQLException e){
         if(this.conn.getAutoCommit()) 
          this.close();
         throw new SQLException(this.MakeErrMsg(strSql,e));
        }
        int columnCount = this.rsmd.getColumnCount();
     try{  
         if (this.rs.next()) {
             for (int i = 1; i <= columnCount; i++) {
                 Object obj = this.rs.getObject(i);
                 if (obj != null){ 
                  String temp=obj.toString().trim();
                     ht.put(this.rsmd.getColumnName(i),temp);
                 }else{
                  String nuller = "";
                     ht.put(this.rsmd.getColumnName(i),nuller);
     }
             }
         }
     }catch(SQLException e){
      this.rs.close();
      this.psmt.close();
      if(this.conn.getAutoCommit())
       this.close();
      throw e;
     }
        this.rs.close();
        this.psmt.close();
        return ht;
    }

    /**
     * 数据库更新,返回操作结果记录数
     * @param strSql String
     * @throws SQLException
     * @return int
     */
    public int update(String strSql) throws SQLException {
         int result = 0;
         try{
            this.psmt = this.conn.prepareStatement(strSql);
            result = this.psmt.executeUpdate();
            this.psmt.close();
        }catch(SQLException e){
         if(this.conn.getAutoCommit())
          this.close();
         throw new SQLException(this.MakeErrMsg(strSql,e));
        }
        return result;
    }
    /**
     * 查询会返回单条记录的sql语句,例如求最值
     * @param strSql String
     * @throws SQLException
     * @return HashMap
     */
    /**
     * 查询会返回单条记录的sql语句,例如求最值
     * @param strSql String
     * @throws SQLException
     * @return HashMap
     */
    public HashMap queryOne1(String strSql) throws SQLException {
        HashMap ht = new HashMap();
        this.psmt = null;
        this.rs = null;
        this.rsmd = null;
        try{
         this.psmt = this.conn.prepareStatement(strSql);
         this.rs = this.psmt.executeQuery();
         this.rsmd = this.rs.getMetaData();
        }catch(SQLException e){
         if(this.conn.getAutoCommit()) 
          this.close();
         throw new SQLException(this.MakeErrMsg(strSql,e));
        }
        int columnCount = this.rsmd.getColumnCount();
     try{  
         if (this.rs.next()) {
             for (int i = 1; i <= columnCount; i++) {
                 Object obj = this.rs.getObject(i);
                 if (obj != null){ 
                  String temp=obj.toString().trim();
                     ht.put(this.rsmd.getColumnName(i),temp);
                 }else{
                  String nuller = "";
                     ht.put(this.rsmd.getColumnName(i),nuller);
     }
             }
         }
     }catch(SQLException e){
      this.rs.close();
      this.psmt.close();
      if(this.conn.getAutoCommit())
       this.close();
      throw e;
     }
        this.rs.close();
        this.psmt.close();
        return ht;
    }
    /**
     * 关闭数据库连接,在一个数据库连接关闭后必须调用
     */
    public void close() {
        try{
            if(this.conn != null && this.conn.isClosed() == false)
             this.conn.close();
        }catch(SQLException e){
            e.printStackTrace();
        }
        if(this.rsmd != null)
         this.rsmd = null;
        if(this.rs != null)
         this.rs = null;
        if(this.psmt != null)
         this.psmt = null;
        if(this.conn != null)
         this.conn = null;
    }
    /**
     *
     * @param strSQL
     * @param e
     * @return 返回出错的原因和出错的SQL语句
     */
    public String MakeErrMsg(String strSQL,SQLException e){
     return e.getMessage() + "\n" + "\u51fa\u9519\u7684SQL\u8bed\u53e5\u662f\"" + strSQL + "\"";
    }
 
    /*******************新加模块重写方法****************************/
   
    /**
     * 查询会返回多条记录的sql语句
     * @param strSql String
     * @throws SQLException
     * @return ArrayList
     */
    public ArrayList query(StringBuffer strSql) throws SQLException {
        ArrayList DbOperationList = new ArrayList();
        if(this.psmt == null) this.psmt = null;
        this.rs = null;
        this.rsmd = null;
        try{
         //this.psmt = this.conn.prepareStatement(strSql);
         this.rs = psmt.executeQuery();
         this.rsmd = rs.getMetaData();
        }catch(SQLException e){
         if(this.conn.getAutoCommit())
          this.close();
         throw new SQLException(this.MakeErrMsg(strSql.toString(),e));
        }
        int columnCount = this.rsmd.getColumnCount();
        try{
         while (this.rs.next()) {
             Hashtable ht = new Hashtable();
             for (int i = 1; i <= columnCount; i++) {
                 Object obj = this.rs.getObject(i);
              
                 if (obj != null){
                    String temp= obj.toString().trim();
                    if("create_date".equals(this.rsmd.getColumnName(i)) || "sys_create_date".equals(this.rsmd.getColumnName(i)) || "user_create_date".equals(this.rsmd.getColumnName(i)))
                     if(temp.length()>11)
                     temp=temp.substring(0,10);
                    
                    ht.put(this.rsmd.getColumnName(i),temp);
                 }else{
                     String nuller = "";
                     ht.put(this.rsmd.getColumnName(i),nuller);
                 }
             }
             DbOperationList.add(ht);
         }
        }catch(SQLException e){
            this.rs.close();
            this.psmt.close();
            if(this.conn.getAutoCommit())
             this.close();
         throw e;
        }
        this.rs.close();
        this.psmt.close();
        return DbOperationList;
    }

    /**
     * 查询会返回单条记录的sql语句,例如求最值
     * @param strSql String
     * @throws SQLException
     * @return Hashtable
     */
    public Hashtable queryOne(StringBuffer strSql) throws SQLException {
      Hashtable ht = new Hashtable();
        if(this.psmt == null) this.psmt = null;
        this.rs = null;
        this.rsmd = null;
        try{
         //this.psmt = this.conn.prepareStatement(strSql);
         this.rs = psmt.executeQuery();
         this.rsmd = rs.getMetaData();
        }catch(SQLException e){
         if(this.conn.getAutoCommit())
          this.close();
         throw new SQLException(this.MakeErrMsg(strSql.toString(),e));
        }
        int columnCount = this.rsmd.getColumnCount();
        try{
         while (this.rs.next()) {
           
             for (int i = 1; i <= columnCount; i++) {
                 Object obj = this.rs.getObject(i);
                 if (obj != null){
                    String temp= obj.toString().trim();
                    if("create_date".equals(this.rsmd.getColumnName(i)) || "sys_create_date".equals(this.rsmd.getColumnName(i)) || "user_create_date".equals(this.rsmd.getColumnName(i)))
                     if(temp.length()>11)
                     temp=temp.substring(0,10);
                    ht.put(this.rsmd.getColumnName(i),temp);
                 }else{
                     String nuller = "";
                     ht.put(this.rsmd.getColumnName(i),nuller);
                 }
             }
           
         }
        }catch(SQLException e){
            this.rs.close();
            this.psmt.close();
            if(this.conn.getAutoCommit())
             this.close();
         throw e;
        }
        this.rs.close();
        this.psmt.close();
        return ht;
    }

    /**
     * 数据库更新,返回操作结果记录数
     * @param strSql String
     * @throws SQLException
     * @return int
     */
    public int update(StringBuffer strSql) throws SQLException {
         int result = 0;
         try{
            //this.psmt = this.conn.prepareStatement(strSql);
            result = this.psmt.executeUpdate();
            this.psmt.close();
        }catch(SQLException e){
         if(this.conn.getAutoCommit())
          this.close();
         throw new SQLException(this.MakeErrMsg(strSql,e));
        }
        return result;
    }

  
    /**
     *
     * @param strSQL
     * @param e
     * @return 返回出错的原因和出错的SQL语句
     */
    public String MakeErrMsg(StringBuffer strSQL,SQLException e){
     return e.getMessage() + "\n" + "\u51fa\u9519\u7684SQL\u8bed\u53e5\u662f\"" + strSQL + "\"";
    }
    private boolean CheckConnIsValid() throws SQLException{
     if(this.conn != null){
      Statement st = null;
       try{
        st = this.conn.createStatement(); 
        String testConnString = "select top 1 from sysusers";
        st.executeUpdate(testConnString);
        st.close();
        return true;
       }catch(SQLException e){
        if(st != null) st.close(); 
        return false;
       }
      
     }else
      throw new SQLException("Can not get connection from pool");
    }
}

你可能感兴趣的:(java,数据库,连接池,职场,休闲)