📄 databasemanager.java
字号:
/* * DatabaseManager.java * * Version: $Revision: 1.36 $ * * Date: $Date: 2005/11/17 19:02:03 $ * * Copyright (c) 2002-2005, Hewlett-Packard Company and Massachusetts * Institute of Technology. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of the Hewlett-Packard Company nor the name of the * Massachusetts Institute of Technology nor the names of their * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. */package org.dspace.storage.rdbms;import java.io.BufferedReader;import java.io.IOException;import java.io.Reader;import java.io.StringReader;import java.io.UnsupportedEncodingException;import java.sql.Connection;import java.sql.DatabaseMetaData;import java.sql.Driver;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.ResultSetMetaData;import java.sql.SQLException;import java.sql.SQLWarning;import java.sql.Statement;import java.sql.Time;import java.sql.Timestamp;import java.sql.Types;import java.text.MessageFormat;import java.util.ArrayList;import java.util.Arrays;import java.util.Collection;import java.util.HashMap;import java.util.HashSet;import java.util.Iterator;import java.util.List;import java.util.Map;import java.util.Set;import org.apache.commons.dbcp.ConnectionFactory;import org.apache.commons.dbcp.DriverManagerConnectionFactory;import org.apache.commons.dbcp.PoolableConnectionFactory;import org.apache.commons.dbcp.PoolingDriver;import org.apache.commons.pool.ObjectPool;import org.apache.commons.pool.impl.GenericObjectPool;import org.apache.log4j.Logger;import org.apache.log4j.Priority;import org.dspace.core.ConfigurationManager;import org.dspace.core.Context;/** * Executes SQL queries. * * @author Peter Breton * @author Jim Downing * @version $Revision: 1.36 $ */public class DatabaseManager{ /** log4j category */ private static Logger log = Logger.getLogger(DatabaseManager.class); /** True if initialization has been done */ private static boolean initialized = false; /** * A map of database column information. The key is the table name, a * String; the value is an array of ColumnInfo objects. */ private static Map info = new HashMap(); /** * Protected Constructor to prevent instantiation except by derived classes. */ protected DatabaseManager() { } /** * Return an iterator with the results of the query. The table parameter * indicates the type of result. If table is null, the column names are read * from the ResultSetMetaData. * * @param context * The context object * @param table * The name of the table which results * @param query * The SQL query * @return A TableRowIterator with the results of the query * @exception SQLException * If a database error occurs */ public static TableRowIterator query(Context context, String table, String query) throws SQLException { if (log.isDebugEnabled()) { log.debug("Running query \"" + query + "\""); } Statement statement = context.getDBConnection().createStatement(); TableRowIterator retTRI = new TableRowIterator(statement.executeQuery(query), canonicalize(table)); retTRI.setStatement(statement); return retTRI; } /** * Return an iterator with the results of the query. * * @param context * The context object * @param query * The SQL query * @return A TableRowIterator with the results of the query * @exception SQLException * If a database error occurs */ public static TableRowIterator query(Context context, String query) throws SQLException { if (log.isDebugEnabled()) { log.debug("Running query \"" + query + "\""); } Statement statement = context.getDBConnection().createStatement(); TableRowIterator retTRI = new TableRowIterator(statement.executeQuery(query)); retTRI.setStatement(statement); return retTRI; } /** * Return an iterator with the results of executing statement. The table * parameter indicates the type of result. If table is null, the column * names are read from the ResultSetMetaData. The context is that of the * connection which was used to create the statement. * * @param statement * The prepared statement to execute. * @param table * The name of the table which results * @return A TableRowIterator with the results of the query * @exception SQLException * If a database error occurs */ public static TableRowIterator query(String table, PreparedStatement statement) throws SQLException { TableRowIterator retTRI = new TableRowIterator(statement.executeQuery(), canonicalize(table)); retTRI.setStatement(statement); return retTRI; } /** * Return an iterator with the results of executing statement. The context * is that of the connection which was used to create the statement. * * @param statement * The prepared statement to execute. * @return A TableRowIterator with the results of the query * @exception SQLException * If a database error occurs */ public static TableRowIterator query(PreparedStatement statement) throws SQLException { TableRowIterator retTRI = new TableRowIterator(statement.executeQuery()); retTRI.setStatement(statement); return retTRI; } /** * Return the single row result to this query, or null if no result. If more * than one row results, only the first is returned. * * @param context * Current DSpace context * @param query * The SQL query * @return A TableRow object, or null if no result * @exception SQLException * If a database error occurs */ public static TableRow querySingle(Context context, String query) throws SQLException { TableRowIterator iterator = query(context, query); TableRow retRow = (!iterator.hasNext()) ? null : iterator.next(); iterator.close(); return (retRow); } /** * Return the single row result to this query, or null if no result. If more * than one row results, only the first is returned. * * @param context * Current DSpace context * @param table * The name of the table which results * @param query * The SQL query * @return A TableRow object, or null if no result * @exception SQLException * If a database error occurs */ public static TableRow querySingle(Context context, String table, String query) throws SQLException { TableRowIterator iterator = query(context, canonicalize(table), query); TableRow retRow = (!iterator.hasNext()) ? null : iterator.next(); iterator.close(); return (retRow); } /** * Execute an update, insert or delete query. Returns the number of rows * affected by the query. * * @param context * Current DSpace context * @param query * The SQL query to execute * @return The number of rows affected by the query. * @exception SQLException * If a database error occurs */ public static int updateQuery(Context context, String query) throws SQLException { Statement statement = null; if (log.isDebugEnabled()) { log.debug("Running query \"" + query + "\""); } try { statement = context.getDBConnection().createStatement(); return statement.executeUpdate(query); } finally { if (statement != null) { try { statement.close(); } catch (SQLException sqle) { } } } } /** * Create a new row in the given table, and assigns a unique id. * * @param context * Current DSpace context * @param table * The RDBMS table in which to create the new row * @return The newly created row */ public static TableRow create(Context context, String table) throws SQLException { TableRow row = new TableRow(canonicalize(table), getColumnNames(table)); insert(context, row); return row; } /** * Find a table row by its primary key. Returns the row, or null if no row * with that primary key value exists. * * @param context * Current DSpace context * @param table * The table in which to find the row * @param id * The primary key value * @return The row resulting from the query, or null if no row with that * primary key value exists. * @exception SQLException * If a database error occurs */ public static TableRow find(Context context, String table, int id) throws SQLException { String ctable = canonicalize(table); return findByUnique(context, ctable, getPrimaryKeyColumn(ctable), Integer.toString(id)); } /** * Find a table row by a unique value. Returns the row, or null if no row * with that primary key value exists. If multiple rows with the value * exist, one is returned. * * @param context * Current DSpace context * @param table * The table to use to find the object * @param column * The name of the unique column * @param value * The value of the unique column * @return The row resulting from the query, or null if no row with that * value exists. * @exception SQLException * If a database error occurs */ public static TableRow findByUnique(Context context, String table, String column, String value) throws SQLException { // Fix common error--value ends with \. Escape this with an extra \. if (value.endsWith("\\")) { value = value + "\\"; } String ctable = canonicalize(table); // Need a pair of single quote marks: // MessageFormat treats this: '{2}' as the literal {2} String sql = MessageFormat.format( "select * from {0} where {1} = ''{2}''", new Object[] { ctable, column, value }); return querySingle(context, ctable, sql); } /** * Delete a table row via its primary key. Returns the number of rows * deleted. *
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -