본문 바로가기

[JAVA] 오라클 연결 싱글톤 구조 변경

I'm 영서 2022. 4. 18.
반응형

작업을 하다보니 드라이브를 싱글톤 구조로 만들어서 한번 만들어두고 더이상 재정의 하지 않는것이 더 나을 것 같다고 판단되어 싱글톤 패턴으로 오라클 커넥션을 변경했다.

 

이와 동시에 sql 단계를 모두 객체화 하여 유지보수용이성을 올렸다..

private static Connection conn;
    public static Connection getConn(){
        if(conn == null){
            try {
                //1. 드라이브준비
                Class.forName(driver);
                //2. 커넥션 연결
                conn = DriverManager.getConnection(url, userid, passwd);
            } catch (ClassNotFoundException e ) { e.printStackTrace(); } 
              catch (SQLException e           ) { e.printStackTrace(); }
        }
        return conn;
    }

private 로 Connection을 생성해 Connection이 단 한개만 생성되도록 싱글톤 패턴 적용..

 

    public static Statement getStatement(Connection conn) throws SQLException{
        return (Statement)conn.createStatement();
    }
    public static ResultSet getSqlData( Statement stmt, String sqlString ) throws SQLException{
        return stmt.executeQuery(sqlString);
    }
    public static int ExecueteDML( Statement stmt, String sqlString) throws SQLException{
        if(countChar(sqlString, ';')> 1){
            stmt = StatementAddBatch(stmt, sqlString);
            return stmt.executeBatch().length;
        }
        return stmt.executeUpdate(sqlString);
    }
    public static Statement StatementAddBatch(Statement stmt, String sqlString) throws SQLException{
        String[] strarr = sqlString.split(";");
        for(String str : strarr){
            stmt.addBatch(str+ ";");
        }
        return stmt;
    }
    public static void closeDriver(ResultSet rs , Statement stmt , Connection conn ) throws SQLException{
        
        if(rs != null)   rs.close();
        if(stmt != null) stmt.close();
        if(conn != null) conn.close();
    }
    public static long countChar(String str, char ch) {
        return str.chars()
        .filter(c -> c == ch)
        .count();
    }

Sql을 준비하고 준비한 Sql을 실행할수 있도록 (DML 이든 DDL이든) 매서드 생성..

 

stmt.executeBatch를 통해 여러개의 sql을 실행할 수 있다.

 

실행결과

DB에 잘들어감..

반응형

댓글