⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 dbutils.java

📁 功能是公安和学校的管理系统,用struts+hibernate+spring等匡架组成,在eclepse就能编译
💻 JAVA
字号:
package com.db;

import java.sql.*;
import javax.sql.DataSource;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.util.*;
import com.db.ComingNetInfo;

public final class DBUtils {

    private static Log log = LogFactory.getLog(DBUtils.class);

    public static final int DATABASE_UNKNOWN     = 0;
    public static final int DATABASE_GENERAL     = 1;
    public static final int DATABASE_NOSCROLL    = 2;

    public static final int DATABASE_ORACLE      = 10;
    public static final int DATABASE_SQLSERVER   = 11;
    public static final int DATABASE_DB2         = 12;
    public static final int DATABASE_SYBASE      = 13;
    public static final int DATABASE_IMFORMIX    = 14;
    public static final int DATABASE_MYSQL       = 15;
    public static final int DATABASE_POSTGRESQL  = 16;
    public static final int DATABASE_HSQLDB      = 17;
    public static final int DATABASE_ACCESS      = 18;

    private static int databaseType = DATABASE_UNKNOWN;

    private static boolean useDatasource = false;

    private static int maxTimeToWait = 2000;// 2 秒钟

    private static int minutesBetweenRefresh = 30;// 30 分钟

    private static DBConnectionManager connectionManager = null;

    private static DataSource dataSource = null;

    private static long lastGetConnectionTime = 0;

    private static long lastCloseAllConnectionsTime = 0;

    static {
        DBOptions option = new DBOptions();
        databaseType = option.databaseType;
        if (databaseType != DATABASE_UNKNOWN) {
            log.info(" 数据库类型 " + databaseType);
        }
        if (option.useDatasource) {
            useDatasource = true;
            try {
                javax.naming.Context context = new javax.naming.InitialContext();
                // sample data source = java:comp/env/jdbc/MysqlDataSource
                dataSource = (DataSource) context.lookup(option.datasourceName);
                log.info("DBUtils : 使用数据库 = " + option.datasourceName);
            } catch (javax.naming.NamingException e) {
                log.error("不能得到数据库 name = " + option.datasourceName, e);
            }
        } else {
            useDatasource = false;
            maxTimeToWait = option.maxTimeToWait;
            minutesBetweenRefresh = option.minutesBetweenRefresh;
            connectionManager = DBConnectionManager.getInstance(option);
            log.info("DBUtils : 使用内置连接 (MAX_TIME_TO_WAIT = " + maxTimeToWait + ", MINUTES_BETWEEN_REFRESH = " + minutesBetweenRefresh + ")");
        }
        log.info("DBUtils 初始化成功. 详情: " + ComingNetInfo.getProductVersion() + " (Build: " + ComingNetInfo.getProductReleaseDate() + ")");
    }

    private DBUtils() {// so cannot new an instance
    }


    public static int getDatabaseType() {
        if (databaseType == DATABASE_UNKNOWN) {
            Connection connection = null;
            try {
                connection = DBUtils.getConnection();
                DatabaseMetaData dbmd = connection.getMetaData();
                String databaseName = dbmd.getDatabaseProductName().toLowerCase();
                if (databaseName.indexOf("oracle") != -1) {
                    databaseType = DATABASE_ORACLE;
                } else if (databaseName.indexOf("sql server") != -1) {
                    databaseType = DATABASE_SQLSERVER;
                } else if (databaseName.indexOf("mysql") != -1) {
                    databaseType = DATABASE_MYSQL;
                } else if (databaseName.indexOf("postgresql") != -1) {
                    databaseType = DATABASE_POSTGRESQL;
                } else if (databaseName.indexOf("hsql") != -1) {
                    databaseType = DATABASE_HSQLDB;
                } else {
                    databaseType = DATABASE_GENERAL;
                }
                log.info("自动检查数据库类型:数据库类型 = " + databaseType);
            } catch (Exception ex) {
                log.error("不能得到数据库的类型", ex);
            } finally {
                DBUtils.closeConnection(connection);
            }
        }
        return databaseType;
    }


    public static Connection getConnection() throws SQLException {

        long now = System.currentTimeMillis();
        lastGetConnectionTime = now;

        if (now - lastCloseAllConnectionsTime > Calendar.MINUTE * minutesBetweenRefresh) {
            boolean isBalance = closeAllConnections();
            if (isBalance == false) {
                try {

                     Thread.sleep(2000);
                    log.debug("DBUtils: 等待2秒钟来注销和关闭数据库连接");
                } catch (Exception ex) { }
            }
        }

        Connection conection = null;

        if (useDatasource) {
            if (dataSource != null) {
                conection = dataSource.getConnection();
            }
        } else {
            if (connectionManager != null) {
                conection = connectionManager.getConnection(maxTimeToWait);
            } else {
                log.fatal("注意: DBUtils.connectionManager == null");
            }
        }

        if (conection == null) {
            throw new SQLException("DBUtils: 不能从连接池中获得数据库连接!");
        }
        return conection;
    }


    public static boolean closeAllConnections() {
        log.debug("调用DBUtils.closeAllConnections来关闭所有的数据库连接");
        boolean retValue = true;// balance (default)
        lastCloseAllConnectionsTime = System.currentTimeMillis();
        if (useDatasource) {
            if (dataSource != null) {
            }
        } else {
            if (connectionManager != null) {
                retValue = connectionManager.release();
            } else {
                log.fatal("注意: DBUtils.connectionManager == null");
            }
        }
        return retValue;
    }


    public static void closeConnection(Connection connection) {
        if (connection == null) return;

        if (useDatasource) {
            try {
                connection.close();
            } catch (SQLException e) {
                log.error("DBUtils: 不能关闭数据库连接", e);
            }
        } else {
            connectionManager.freeConnection(connection);
        }
    }

    public static void resetStatement(Statement statement) {
        if (statement != null) {
            try {
                statement.setMaxRows(0);
            } catch (SQLException e) {
                log.error("DBUtils: 不能重置stmt 的最大行数", e);
            }

            try {
                statement.setFetchSize(0);
            } catch (SQLException sqle) {
              System.out.println(sqle.getMessage());
            }
        }
    }

    public static void closeStatement(Statement statement) {
        try {
            if (statement != null) statement.close();
        } catch (SQLException e) {
            log.error("DBUtils: 不能关闭 statement.", e);
        }
    }

    public static void closeResultSet(ResultSet rs) {
        try {
            if (rs != null) rs.close();
        } catch (SQLException e) {
            log.error("DBUtils:不能关闭 resultset.", e);
        }
    }


}

⌨️ 快捷键说明

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