'Code Template'에 해당되는 글 2

  1. 2009.05.05 JDBC Code Template - 프로시저
  2. 2009.04.29 JDBC Code Template

JDBC Code Template - 프로시저

CallableStatement cs = null;
try{
    cs = con.prepareCall("{ ? = call sp_test(?,?,?) }");
    int idx = 0;
    cs.registerOutParameter(++idx, Types.INTEGER);
    cs.setString(++idx, COL_1);
    cs.setString(++idx, COL_2);
    cs.setString(++idx, COL_3);
    
    cs.execute();
    int result = cs.getInt(1);
    if(result == -1){ //check error
        throw new SQLException("result is -1"); //=-=> 좀 더 정형화된 다른 예외를 만들어야...
    }
    return result;

}catch(Exception e){  
    throw new RuntimeSQLException(e, primaryKey); 
}finally{
    if(cs != null){ try{ cs.close(); }catch(Exception ignored){  } }
}

JDBC Code Template


PreparedStatement ps = null;
try{
    ps = con.prepareStatement(QUERY);
    int idx = 0;
    ps.setString(++idx, COL_1);
    ...
    ps.setString(++idx, COL_N);
    
    return ps.executeUpdate();

}catch(Exception e){
    throw new RuntimeSQLException(e, primaryKey);
}finally{
    if(ps != null){ try{ ps.close(); }catch(Exception ignored){  }
}
Connection con = null;
PrepareStatement ps = null;

try{
	ps = con.prepareStatement(QUERY);  
	int idx = 0;  
	ps.setString(++idx, COL_1);  
	...  
	ps.setString(++idx, COL_N);  

	int affectedRow = ps.executeUpdate();
	if(affectedRow != 1){
		throw new RuntimeSQLException(" expected : 1, result : " + affectedRow
			, primaryKey); //=-=> 정형화...
	}
	con.commit();
}catch(Exception e){
	con.rollback();
	throw new RuntimeSQLException(e, primaryKey);
}finally{
    if(ps != null){ try{ ps.close(); }catch(Exception ignored){  }
    if(con != null){ try{ con.close(); }catch(Exception ignored){  }
}