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

📄 databasemanager.java

📁 dspace 用j2ee架构的一个数字图书馆.开源程序
💻 JAVA
📖 第 1 页 / 共 4 页
字号:
                    statement.setLong(count, row.getLongColumn(column));                }                else if (jdbctype == Types.VARCHAR)                {                    statement.setString(count, row.getStringColumn(column));                    continue;                }                else if (jdbctype == Types.DATE)                {                    java.sql.Date d = new java.sql.Date(row.getDateColumn(                            column).getTime());                    statement.setDate(count, d);                    continue;                }                else if (jdbctype == Types.TIME)                {                    Time t = new Time(row.getDateColumn(column).getTime());                    statement.setTime(count, t);                    continue;                }                else if (jdbctype == Types.TIMESTAMP)                {                    Timestamp t = new Timestamp(row.getDateColumn(column)                            .getTime());                    statement.setTimestamp(count, t);                    continue;                }                else                {                    throw new IllegalArgumentException(                            "Unsupported JDBC type: " + jdbctype);                }            }            return statement.executeUpdate();        }        finally        {            if (statement != null)            {                try                {                    statement.close();                }                catch (SQLException sqle)                {                }            }        }    }    /**     * Return metadata about a table.     *      * @param table     *            The name of the table     * @return An map of info.     * @exception SQLException     *                If a database error occurs     */    private static Map getColumnInfoInternal(String table) throws SQLException    {        String ctable = canonicalize(table);        Map results = (Map) info.get(ctable);        if (results != null)        {            return results;        }        results = retrieveColumnInfo(ctable);        info.put(ctable, results);        return results;    }    /**     * Read metadata about a table from the database.     *      * @param table     *            The RDBMS table.     * @return A map of information about the columns. The key is the name of     *         the column, a String; the value is a ColumnInfo object.     * @exception SQLException     *                If there is a problem retrieving information from the     *                RDBMS.     */    private static Map retrieveColumnInfo(String table) throws SQLException    {        Connection connection = null;        try        {            connection = getConnection();            DatabaseMetaData metadata = connection.getMetaData();            HashMap results = new HashMap();            int max = metadata.getMaxTableNameLength();            String tname = (table.length() >= max) ? table                    .substring(0, max - 1) : table;            ResultSet pkcolumns = metadata.getPrimaryKeys(null, null, tname);            Set pks = new HashSet();            while (pkcolumns.next())                pks.add(pkcolumns.getString(4));            ResultSet columns = metadata.getColumns(null, null, tname, null);            while (columns.next())            {                String column = columns.getString(4);                ColumnInfo cinfo = new ColumnInfo();                cinfo.setName(column);                cinfo.setType((int) columns.getShort(5));                if (pks.contains(column))                {                    cinfo.setIsPrimaryKey(true);                }                results.put(column, cinfo);            }            return results;        }        finally        {            if (connection != null)            {                connection.close();            }        }    }    /**     * Initialize the DatabaseManager.     */    private static void initialize() throws SQLException    {        if (initialized)        {            return;        }        try        {            // Register basic JDBC driver            Class driverClass = Class.forName(ConfigurationManager                    .getProperty("db.driver"));            Driver basicDriver = (Driver) driverClass.newInstance();            DriverManager.registerDriver(basicDriver);            // Read pool configuration parameter or use defaults            // Note we check to see if property is null; getIntProperty returns            // '0' if the property is not set OR if it is actually set to zero.            // But 0 is a valid option...            int maxConnections = ConfigurationManager                    .getIntProperty("db.maxconnections");            if (ConfigurationManager.getProperty("db.maxconnections") == null)            {                maxConnections = 30;            }            int maxWait = ConfigurationManager.getIntProperty("db.maxwait");            if (ConfigurationManager.getProperty("db.maxwait") == null)            {                maxWait = 5000;            }            int maxIdle = ConfigurationManager.getIntProperty("db.maxidle");            if (ConfigurationManager.getProperty("db.maxidle") == null)            {                maxIdle = -1;            }            // Create object pool            ObjectPool connectionPool = new GenericObjectPool(null, // PoolableObjectFactory                    // - set below                    maxConnections, // max connections                    GenericObjectPool.WHEN_EXHAUSTED_BLOCK, maxWait, // don't                                                                     // block                    // more than 5                    // seconds                    maxIdle, // max idle connections (unlimited)                    true, // validate when we borrow connections from pool                    false // don't bother validation returned connections            );            // ConnectionFactory the pool will use to create connections.            ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(                    ConfigurationManager.getProperty("db.url"),                    ConfigurationManager.getProperty("db.username"),                    ConfigurationManager.getProperty("db.password"));            //            // Now we'll create the PoolableConnectionFactory, which wraps            // the "real" Connections created by the ConnectionFactory with            // the classes that implement the pooling functionality.            //            String validationQuery = "SELECT 1";            // Oracle has a slightly different validation query            if ("oracle".equals(ConfigurationManager.getProperty("db.name")))            {                validationQuery = "SELECT 1 FROM DUAL";            }            PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(                    connectionFactory, connectionPool, null, // no                                                             // preparedstatement                    // pooling for now                    validationQuery, // validation query                    false, // read only is not default for now                    false); // Autocommit defaults to none            //            // Finally, we create the PoolingDriver itself...            //            PoolingDriver driver = new PoolingDriver();            //            // ...and register our pool with it.            //            driver.registerPool("dspacepool", connectionPool);            // Old SimplePool init            //DriverManager.registerDriver(new SimplePool());            initialized = true;        }        catch (SQLException se)        {            // Simply throw up SQLExceptions            throw se;        }        catch (Exception e)        {            // Need to be able to catch other exceptions. Pretend they are            // SQLExceptions, but do log            log.warn("Exception initializing DB pool", e);            throw new SQLException(e.toString());        }    }}/** * Represents a column in an RDBMS table. */class ColumnInfo{    /** The name of the column */    private String name;    /** The JDBC type of the column */    private int type;    /** True if this column is a primary key */    private boolean isPrimaryKey;    /**     * Constructor     */    ColumnInfo()    {    }    /**     * Constructor     */    ColumnInfo(String name, int type)    {        this.name = name;        this.type = type;    }    /**     * Return the column name.     *      * @return - The column name     */    public String getName()    {        return name;    }    /**     * Set the column name     *      * @param v -     *            The column name     */    void setName(String v)    {        name = v;    }    /**     * Return the JDBC type. This is one of the constants from java.sql.Types.     *      * @return - The JDBC type     * @see java.sql.Types     */    public int getType()    {        return type;    }    /**     * Set the JDBC type. This should be one of the constants from     * java.sql.Types.     *      * @param v -     *            The JDBC type     * @see java.sql.Types     */    void setType(int v)    {        type = v;    }    /**     * Return true if this column is a primary key.     *      * @return True if this column is a primary key, false otherwise.     */    public boolean isPrimaryKey()    {        return isPrimaryKey;    }    /**     * Set whether this column is a primary key.     *      * @param v     *            True if this column is a primary key.     */    void setIsPrimaryKey(boolean v)    {        this.isPrimaryKey = v;    }    /*     * Return true if this object is equal to other, false otherwise.     *      * @return True if this object is equal to other, false otherwise.     */    public boolean equals(Object other)    {        if (!(other instanceof ColumnInfo))        {            return false;        }        ColumnInfo theOther = (ColumnInfo) other;        return ((name != null) ? name.equals(theOther.name)                : (theOther.name == null))                && (type == theOther.type)                && (isPrimaryKey == theOther.isPrimaryKey);    }    /*     * Return a hashCode for this object.     *      * @return A hashcode for this object.     */    public int hashCode()    {        return new StringBuffer().append(name).append(type)                .append(isPrimaryKey).toString().hashCode();    }}

⌨️ 快捷键说明

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