`
jiaoxujin
  • 浏览: 61736 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
最近访客 更多访客>>
社区版块
存档分类
最新评论

连接数据库的相关代码

阅读更多
package ecogp.dml;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import org.apache.log4j.Logger;
import oracle.jdbc.driver.OracleDriver;
/**
* <P>データベースをアクセス</P>
*
* @author B.Gao
*
*/
public class DBAccess {
private Connection conn = null;
    /** ステートメントオブジェクト */
    private Statement stmt;
   
    static Logger logger = Logger.getLogger(DBAccess.class.getName());
    /** プリペアードステートメントオブジェクト */
    private PreparedStatement pstmt;

public void createConnection(String dbServer, String dbName, String dbUser, String dbPassword) {
     String url = "jdbc:oracle:thin:@" + dbServer + ":" + "1521" + ":" + dbName;
     try {
       DriverManager.registerDriver(new OracleDriver());
       conn = DriverManager.getConnection(url, dbUser, dbPassword);
       conn.setAutoCommit(false);
     } catch (Exception e) {
         System.out.println(e.toString());
      logger.debug("DBの接続に失敗します。");
      conn = null;
     }
}

public Connection getConn() {
  return this.conn;
}

public boolean isConnection() throws SQLException{
  boolean ret*** = true;
  if (conn == null || conn.isClosed()) {
   ret*** = false;
  }
  return ret***;
}

    /**
     * 値を返す SQL を実行する。
     * <p>
     * 値を返す SQL とは、たとえば、select があげられる。
     * <p>
     * @param sql 実行したい SQL文字列
     * @return ResutSet オブジェクト
     * @throws SQLException なんらかのデータベースエラーが発生した時
     */
    public ResultSet executeQuery(String sql) throws SQLException {
        System.out.println(sql);
        ResultSet rslt = null;
        try {
            if (stmt != null) {
                stmt.close();
            }
            stmt = conn.createStatement();
            rslt = stmt.executeQuery(sql);
        }
        catch (SQLException e) {
            throw e;
        }
        return rslt;
    }
    /**
     * 値を返さない SQL を実行する。
     * <p>
     * 値を返さない SQL とは、たとえば、insert、update があげられる。
     * SQL は、外部ファイルに記載した PreparedStatement 用 SQL 構文を使用する。
     * <p>
     * @param sql 実行したい SQL文字列
     * @return 処理件数
     * @throws SQLException なんらかのデータベースエラーが発生した時
     */
    public int executeUpdate(String sql) throws SQLException {
        System.out.println(sql);
       int status = 0;
        try {
            if (stmt != null) {
                stmt.close();
            }
            stmt = conn.createStatement();
            status = stmt.executeUpdate(sql);
        }
        catch (SQLException e) {
            throw e;
        }
        return statu*;
    }
    /**
     * **ecuteUpdate にて、前回実行したSQLと変更がない場合には、prepareStatement の生成を行わない。
     * そのために、前回実行したSQLの番号を保存するための変数。
     */
    private String lastPrepareSQL = "";
    private HashMap preparedStatementCache = new HashMap(); 

/**
     * 値を返す SQL を実行する。
     * <p>
     * 値を返す SQL とは、たとえば、select があげられる。
     * SQL は、外部ファイルに記載した PreparedStatement 用 SQL 構文を使用する。
     * <p>
     * @param sqlid 実行したい SQLのID
     * @param sqlparams SQL のパラメータ(パラメータがない場合には、null)
     * @return ResutSet オブジェクト
     * @throws SQLException なんらかのデータベースエラーが発生した時
     */
    public ResultSet executeQuery(String sql, Object[] sqlparams) throws SQLException {
        System.out.println(sql);
        if (sqlparams == null || sqlparams.length == 0) {
            if (stmt != null) {
                stmt.close();
            }
            stmt = conn.createStatement();
            return stmt.executeQuery(sql);
        }
        else {
            try {
                if (lastPrepareSQL.equals(sql) && pstmt != null) {
                    // 前回実行した SQL と同じであれば、ステートメントを再利用する
                }
                else {
                    if (pstmt != null) {
                        pstmt.close();
                    }
                    pstmt = conn.prepareStatement(sql);
                    lastPrepareSQL = sql;
                }
                for (int i = 0; i < sqlparams.length; i++) {
                    try {
                        pstmt.setObject(i + 1, sqlparams[i]);
                    }
                    catch (SQLException e) {
                        throw e;
                    }
                }
                return pstmt.executeQuery();
            }
            catch (SQLException e) {
                throw e;
            }
        }
    }

    /**
     * 値を返さない SQL を実行する。
     * <p>
     * 値を返さない SQL とは、たとえば、insert、update があげられる。
     * <p>
     * @param sqlid 実行したい SQLのID
     * @param sqlparams SQL のパラメータ(パラメータがない場合には、null)
     * @return 処理件数
     * @throws SQLException なんらかのデータベースエラーが発生した時
     */
    public int executeUpdate(String sql, Object[] sqlparams) throws SQLException {
        System.out.println(sql);
        if (sqlparams == null || sqlparams.length == 0) {
            if (stmt != null) {
                stmt.close();
            }
            stmt = conn.createStatement();
            return stmt.executeUpdate(sql);
        }
        else {
            try {
                if (lastPrepareSQL.equals(sql) && pstmt != null) {
                    // 前回実行した SQL と同じであれば、ステートメントを再利用する
                }
                else {
                    if (pstmt != null) {
                        pstmt.close();
                    }
                    pstmt = conn.prepareStatement(sql);
                    lastPrepareSQL = sql;
                }
//                StringBuffer logString = new StringBuffer(512);
                for (int i = 0; i < sqlparams.length; i++) {
                    try {
                        pstmt.setObject(i + 1, sqlparams[i]);
//                        logString.append(sqlparams[i] + ",");
                    }
                    catch (SQLException e) {
//                        cat.error(
//                            "executeUpdate(id,obj[]) setObject:SqlParams[" + i +
//                            "]=" + sqlparams[i]);
                        throw e;
                    }
                    pstmt.addBatch();
                }
                return pstmt.executeUpdate();
            }
            catch (SQLException e) {
                throw e;
            }
        }
    }

    /**
     * commit を実行する。
     * <p>
     * データベースへの接続は、AutoCommit を行っていないため、すべての処理が正常に完了した場合には、
     * 最後に必ず このメソッドを呼び出す。
     * <p>
     * @throws SQLException なんらかのデータベースエラーが発生した時
     */
    public void commit() throws SQLException {
        if (conn != null)
         conn.commit();
    }
    /**
     * rollback を実行する。
     * <p>
     * 処理が正常に完了しなかった場合には、このメソッドを呼び出して、データベースへの更新の
     * 取消を行う。
     * <p>
     * @throws SQLException なんらかのデータベースエラーが発生した時
     */
    public void rollback() throws SQLException {
        if (conn != null && conn.isClosed()==false){
         conn.rollback();
        }
    }
    /**
     * Connectionのcloseを行う
     * @throws SQLException なんらかのデータベースエラーが発生した時
     */
    public void releaseConnection() throws SQLException {
        if (stmt != null) {
            stmt.close();
        }
        if (pstmt != null) {
            pstmt.close();
        }
        if (conn != null) {
         conn.close();
        }
    }
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics