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

📄 databasemanager.java

📁 DSPACE的源码 dspace-1.4-source
💻 JAVA
📖 第 1 页 / 共 4 页
字号:
                    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;            }                        boolean useStatementPool = ConfigurationManager.getBooleanProperty("db.statementpool",true);            // 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";            }            GenericKeyedObjectPoolFactory statementFactory = null;            if (useStatementPool)            {	            // The statement Pool is used to pool prepared statements.	            GenericKeyedObjectPool.Config statementFactoryConfig = new GenericKeyedObjectPool.Config();	            // Just grow the pool size when needed. 	            // 	            // This means we will never block when attempting to 	            // create a query. The problem is unclosed statements, 	            // they can never be reused. So if we place a maximum 	            // cap on them, then we might reach a condition where 	            // a page can only be viewed X number of times. The 	            // downside of GROW_WHEN_EXHAUSTED is that this may 	            // allow a memory leak to exist. Both options are bad, 	            // but I'd prefer a memory leak over a failure.	            //	            // FIXME: Perhaps this decision should be derived from config parameters?	            statementFactoryConfig.whenExhaustedAction = GenericObjectPool.WHEN_EXHAUSTED_GROW;		            statementFactory = new GenericKeyedObjectPoolFactory(null,statementFactoryConfig);            }                        PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(                    connectionFactory, connectionPool, statementFactory,                    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());        }    }	/**	 * Iterate over the given parameters and add them to the given prepared statement. 	 * Only a select number of datatypes are supported by the JDBC driver.	 *	 * @param statement	 * 			The unparameterized statement.	 * @param parameters	 * 			The parameters to be set on the statement.	 */	protected static void loadParameters(PreparedStatement statement, Object[] parameters) 	throws SQLException{				statement.clearParameters();			    for(int i=0; i < parameters.length; i++)	    {		    	// Select the object we are setting.	    	Object parameter = parameters[i];	    	int idx = i+1; // JDBC starts counting at 1.	    		    	if (parameter == null)	    	{	    		throw new SQLException("Attempting to insert null value into SQL query.");	    	}	    	if (parameter instanceof String)	    	{	    		statement.setString(idx,(String) parameters[i]);	    	}	    	else if (parameter instanceof Integer)	    	{	    		int ii = ((Integer) parameter).intValue();	    		statement.setInt(idx,ii);	    	}	    	else if (parameter instanceof Double)	    	{	    		double d = ((Double) parameter).doubleValue();	    		statement.setDouble(idx,d);	    	}	    	else if (parameter instanceof Float)	    	{	    		float f = ((Float) parameter).floatValue();	    		statement.setFloat(idx,f);	    	}	    	else if (parameter instanceof Short)	    	{	    		short s = ((Short) parameter).shortValue();	    		statement.setShort(idx,s);	    	}	    	else if (parameter instanceof Long)	    	{	    		long l = ((Long) parameter).longValue();	    		statement.setLong(idx,l);	    	}	    	else if (parameter instanceof Date)	    	{	    		Date date = (Date) parameter;	    		statement.setDate(idx,date);	    	}	    	else if (parameter instanceof Time)	    	{	    		Time time = (Time) parameter;	    		statement.setTime(idx,time);	    	}	    	else if (parameter instanceof Timestamp)	    	{	    		Timestamp timestamp = (Timestamp) parameter;	    		statement.setTimestamp(idx,timestamp);	    	}	    	else	    	{	    		throw new SQLException("Attempting to insert unknown datatype ("+parameter.getClass().getName()+") into SQL statement.");	    	}        		    }	}}/** * 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 + -