DAOTemplate

import java.sql.*;
import javax.naming.InitialContext;
import javax.sql.DataSource;

/**
 * Data Access Objectの共通機能を実装したクラス
 * @author ITBoost
 */
public class DAOTemplate {

	/**
	 * <pre>DAOで管理するデータベースのデータソース名を返す
	 * ※サブクラスでオーバーライドする※</pre>
	 * @return データソース名
	 */
	public String getDataSourceName() {
		return "dummy";
	}

	/**
	 * データベースに接続する
	 * @return Conncetionオブジェクト
	 */
	public Connection createConnection() throws SQLException {
		Connection con = null;
		try {
			// 初期コンテキストを取得
			InitialContext ic = new InitialContext();
			// ルックアップしてデータソースを取得
			DataSource ds =
				(DataSource) ic.lookup("java:comp/env/" + getDataSourceName());
			con = ds.getConnection();
		} catch (Exception e) {
			// テスト用のデータベース情報
			try {
				Class.forName("org.postgresql.Driver");
				// 初期コンテキストを取得
				con =
					DriverManager.getConnection(
						"jdbc:postgresql://sv:5432/strutsdev",
						"postgres",
						"");
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
		return con;
	}

	/**
	 * データベースから切断する
	 * @param con Conncetionオブジェクト
	 */
	protected void closeConnection(Connection con) {
		try {
			if (con != null)
				con.close();
			con = null;
		} catch (SQLException ex) {
			;
		}
	}

	/**
	 * <pre>次のIDを獲得する
	 * ※トランザクションの中で呼び出すこと※</pre>
	 * @param con Conncetionオブジェクト
	 * @param tableName テーブル名
	 * @return 次のID
	 */
	protected synchronized int getNextId(Connection con, String tableName)
		throws SQLException {
		Statement stmt = con.createStatement();
		stmt.execute("LOCK TABLE " + tableName);
		ResultSet rs =
			stmt.executeQuery("select max(id)+1 as next_id from " + tableName);
		rs.next();
		return rs.getInt("next_id");
	}

	/**
	 *  <pre>SQL式をエスケープする。
	 *  PostgreSQLを想定。DBMSによってエスケープすべき文字は異なるので注意が必要。</pre>
	 *  @param aStr エスケープしたいSQL式
	 *  @return エスケープ済みの文字列
	 */
	public static String escapeSQL(String aStr) {
		char c;
		if (aStr == null)
			return null;
		StringBuffer returnStr = new StringBuffer();
		int length = aStr.length();
		for (int i = 0; i < length; i++) {
			c = aStr.charAt(i);
			if (c == '\'') {
				returnStr = returnStr.append("''");
			} else if (c == '\\') {
				returnStr = returnStr.append("\\\\");
			} else if (c == '"') {
				returnStr = returnStr.append("\\\"");
			} else if (c == ';') {
				returnStr = returnStr.append("\\;");
			} else {
				returnStr = returnStr.append(c);
			}
		}
		return new String(returnStr);
	}
}