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

📄 connectionpool.java

📁 用Java编写的GPS监控系统后台私服的核心代码。
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
        }*/

        //打印数据库连接信息
        if (this.strDataSource.equals("Oracle")) {
            trace("Oracle Host = " + this.strOracleHost);
            trace("Oracle Port = " + this.strOraclePort);
            trace("Oracle ServiceID = " + this.strOracleServiceID);
            trace("Oracle UserName = " + this.strUserName);
            trace("Oracle Password = " + this.strPassword);
            this.strDriverName = "oracle.jdbc.driver.OracleDriver";
        } else if (this.strDataSource.equals("PointBase")) {
            trace("JDBCDriver = " + this.strDriverName);
            trace("JDBCConnectionURL = " + this.strConnectionURL);
            trace("JDBCUserName = " + this.strUserName);
            trace("JDBCPassword = " + this.strPassword);
        } else if (this.strDataSource.equals("sun_odbc_jdbc")) {
            trace("JDBCDriver = " + this.strDriverName);
            trace("JDBCDSN = " + this.strDSN);
            trace("JDBCUserName = " + this.strUserName);
            trace("JDBCPassword = " + this.strPassword);
        }
        //打印数据库连接池信息
        trace("ConnectionPoolSize = " + nConnectionPoolSize);
        trace("ConnectionPoolMax = " + nConnectionPoolMax);
        trace("ConnectionUseCount = " + nConnectionUseCount);
        trace("ConnectionTimeout = " + nConnectionTimeout + " seconds");

        //注册数据库驱动程序
        trace("Registering " + strDriverName);
        //Driver driver = null;
        if (this.strDataSource.equals("Oracle")) {
            DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
        } else if (this.strDataSource.equals("PointBase")) {
            Class.forName(strDriverName).newInstance();   //driver = (Driver)
        } else if (this.strDataSource.equals("sun_odbc_jdbc")) {
            Class.forName(strDriverName).newInstance();   //driver = (Driver)
        }

        // Create the vector for the pool
        pool = new Vector();

        // Bring the pool to the minimum size
        fillPool(nConnectionPoolSize);
    }

    /**
     * 添加一个新的数据库连接到连接池
     *
     * @return 返回新添加的连接在连接池中的索引,如果在创建
     *         连接过程中发生错误则返回-1;
     */
    private int addConnection() {
        int nIndex = -1;

        try {
            // Calculate the new size of the pool
            int nSize = pool.size() + 1;

            // Create a new entry
            fillPool(nSize);

            // Set the index pointer to the new connection if one
            // was created
            if (nSize == pool.size()) {
                nIndex = nSize - 1;
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return nIndex;
    }

    /**
     * 根据给定的长度,产生数据库连接池
     */
    private synchronized void fillPool(int nSize) throws Exception {
        String strURL = null;
        // Loop while we need to create more connections
        while (pool.size() < nSize) {
            ConnectionObject co = new ConnectionObject();

            //创建数据库连接
            if (this.strDataSource.equals("Oracle")) {
                strURL = "jdbc:oracle:thin:@"
                        + this.strOracleHost + ":"
                        + this.strOraclePort + ":"
                        + this.strOracleServiceID;
                co.con = DriverManager.getConnection(strURL, this.strUserName, this.strPassword);
            } else if (this.strDataSource.equals("PointBase")) {
                co.con = DriverManager.getConnection(strConnectionURL, strUserName, strPassword);
            } else if (this.strDataSource.equals("sun_odbc_jdbc")) {
                strURL = "jdbc:odbc:" + this.strDSN;
                co.con = DriverManager.getConnection(strURL, this.strUserName, this.strPassword);
            }

            // Do some sanity checking on the first connection in
            // the pool
            if (pool.size() == 0) {
                // Get the maximum number of simultaneous connections
                // as reported by the JDBC driver
                DatabaseMetaData md = co.con.getMetaData();
                nMaxConnections = md.getMaxConnections();
            }

            // Give a warning if the size of the pool will exceed
            // the maximum number of connections allowed by the
            // JDBC driver
            if ((nMaxConnections > 0) && (nSize > nMaxConnections)) {
                trace("WARNING: Size of pool will exceed safe maximum of " +
                        nMaxConnections);
            }

            // Clear the in use flag
            co.bInUse = false;

            // Set the last access time
            touch(co);

            pool.addElement(co);
        }  //End of while
    }

    /**
     * 根据名称获取指定属性的值,忽略大小写. 如果没有发现则返回null
     *
     * @param p       属性名称
     * @param strName 属性的值
     * @return 返回指定属性的值,如果没有则返回null
     */
    private String getPropertyIgnoreCase(Properties p,
                                         String strName) {
        if ((p == null) || (strName == null)) return null;

        String strValue = null;

        // Get an enumeration of the property names
        Enumeration enum = p.propertyNames();

        // Loop through the enum, looking for the given property name
        while (enum.hasMoreElements()) {
            String pName = (String) enum.nextElement();
            if (pName.equalsIgnoreCase(strName)) {
                strValue = p.getProperty(pName);
                break;
            }
        }

        return strValue;
    }

    /**
     * 在数据库连接池中查询指定的连接
     *
     * @return 返回指定连接在连接池中的索引号,如果没有找到则返回-1.
     */
    private int find(Connection con) {
        int nIndex = -1;

        // Find the matching Connection in the pool
        if ((con != null) &&
                (pool != null)) {
            for (int i = 0; i < pool.size(); i++) {
                ConnectionObject co = (ConnectionObject)
                        pool.elementAt(i);
                if (co.con == con) {
                    nIndex = i;
                    break;
                }
            }
        }
        return nIndex;
    }

    /**
     * 线程函数,处理连接超时,
     * 连接池调度机制处理.
     */
    public synchronized void run() {
        // No pool means no work
        if (pool == null) {
            return;
        }

        // Get the current time in milliseconds
        long now = System.currentTimeMillis();

        // Check for any expired connections and remove them
        for (int i = pool.size() - 1; i >= 0; i--) {
            ConnectionObject co = (ConnectionObject)
                    pool.elementAt(i);

            // If the connection is not in use and it has not been
            // used recently, remove it
            if (!co.bInUse) {
                if ((nConnectionTimeout > 0) &&
                        (co.nLastAccess +
                        (nConnectionTimeout * 1000) < now)) {
                    removeFromPool(i);
                }
            }
        }

        // Remove any connections that are no longer open
        for (int i = pool.size() - 1; i >= 0; i--) {
            ConnectionObject co = (ConnectionObject)
                    pool.elementAt(i);
            try {
                // If the connection is closed, remove it from the pool
                if (co.con.isClosed()) {
                    trace("Connection closed unexpectedly");
                    removeFromPool(i);
                }
            } catch (Exception ex) {
            }
        }

        // Now ensure that the pool is still at it's minimum size
        try {
            if (pool != null) {
                if ((pool.size() < nConnectionPoolSize)) {
                    fillPool(nConnectionPoolSize);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        // Reschedule ourselves
        scheduler.schedule(this, TIMEOUT_MS);
    }

    /**
     * 设置最近存取时间指定的ConnectionObject
     */
    private void touch(ConnectionObject co) {
        if (co != null) {
            co.nLastAccess = System.currentTimeMillis();
            co.strLastAccess = new MyTime().toString();
        }
    }

    /**
     * 打印调试信息
     */
    private void trace(String s) {
        System.out.println("ConnectionPool: " + s);
    }

    /**
     * 测试函数
     *
     * @param strSQL SQL语句
     * @param con    数据库连接
     */
    public static void PrintData(String strSQL, Connection con) {
        //String strSQL = "Select * from TB_BASE_VEHICLE_INFOS";
        PreparedStatement ps = null;
        String strOut;
        try {
            ps = con.prepareStatement(strSQL);
            if (ps.execute()) {
                ResultSet rs = ps.getResultSet();
                ResultSetMetaData rsmd = ps.getMetaData();

                int nColumn = rsmd.getColumnCount() + 1;
                while (rs.next()) {
                    for (int nCol = 1; nCol < nColumn; nCol++) {
                        strOut = rsmd.getColumnName(nCol) + " = " + String.valueOf(rs.getObject(nCol));
                        System.out.println(strOut);
                    }
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if (ps != null) {
                    ps.close();
                    ps = null;
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 测试函数
     *
     * @param args 参数
     */
    public static void main(String[] args) {
        ConnectionPool cp = new ConnectionPool();
        try {
            if (!cp.initialize()) {
                System.out.println("数据库连接池初始化失败!");
                return;
            }
            Connection con = cp.getConnection();
            if (con == null) {
                System.out.println("从数据库连接池中获取一个Connection对象失败!");

            } else {
                PrintData("Select * from TB_BASE_VEHICLE_INFOS", con);
            }

            con = cp.getConnection();
            if (con == null) {
                System.out.println("从数据库连接池中获取一个Connection对象失败!");

            } else {
                PrintData("Select * from TB_CODE_SYS_ERR_LEVEL", con);
                //PrintData("Select * from TB_CODE_DEVICE_STATUS",con);
            }
            con = cp.getConnection();
            if (con == null) {
                System.out.println("从数据库连接池中获取一个Connection对象失败!");

            } else {
                //PrintData("Select * from TB_CODE_SYS_ERR_LEVEL",con);
                PrintData("Select * from TB_CODE_DEVICE_STATUS", con);
            }

            con = cp.getConnection();
            if (con == null) {
                System.out.println("从数据库连接池中获取一个Connection对象失败!");

            } else {
                PrintData("Select * from TB_BASE_PERSON_INFOS", con);
                //PrintData("Select * from TB_BASE_DEVICE_INFOS",con);
            }

            con = cp.getConnection();
            if (con == null) {
                System.out.println("从数据库连接池中获取一个Connection对象失败!");

            } else {
                //PrintData("Select * from TB_BASE_PERSON_INFOS",con);
                PrintData("Select * from TB_BASE_DEVICE_INFOS", con);
            }

            con = cp.getConnection();
            if (con == null) {
                System.out.println("从数据库连接池中获取一个Connection对象失败!");

            } else {
                //PrintData("Select * from TB_BASE_PERSON_INFOS",con);
                PrintData("Select * from TB_BASE_OPERATOR_INFOS", con);
            }

            con = cp.getConnection();
            if (con == null) {
                System.out.println("从数据库连接池中获取一个Connection对象失败!");

            } else {
                //PrintData("Select * from TB_BASE_PERSON_INFOS",con);
                PrintData("Select * from TB_BASE_TERMINAL_INFOS", con);
            }

            cp.printPool();

            cp.destroy();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}


⌨️ 快捷键说明

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