개발/JAVA

JAVA로 테이블(table)의 기본키 컬럼정보가져오기 (PrimaryKey, pk)

macle 2016. 5. 29. 00:27


만능유틸을 만들다보니까 java로 DB테이블의 키본키정보를 가져와야할 필요가 생겼습니다.

관련 제공방법을 찾아보니 인터넷에 예제소스가 있더군요.


우선찾은 소스인데 실험해보니

  public static Set<String> getPrimaryKeyColumnsForTable(Connection connection, String tableName) throws SQLException {
    try(ResultSet pkColumns= connection.getMetaData().getPrimaryKeys(null,null,tableName);) {
      SortedSet<String> pkColumnSet = new TreeSet<>();
      while(pkColumns.next()) {
        String pkColumnName = pkColumns.getString("COLUMN_NAME");
        Integer pkPosition = pkColumns.getInt("KEY_SEQ");
        out.println(""+pkColumnName+" is the "+pkPosition+". column of the primary key of the table "+tableName);
        pkColumnSet.add(pkColumnName);
      }
      return pkColumnSet;
    }


CD_ONTOLOGY is the 3. column of the primary key of the table TB_ARA_DOC_ONTOLOGY

CD_ONTOLOGY is the 3. column of the primary key of the table TB_ARA_DOC_ONTOLOGY

CD_ONTOLOGY_ANALYSIS is the 4. column of the primary key of the table TB_ARA_DOC_ONTOLOGY

CD_ONTOLOGY_ANALYSIS is the 4. column of the primary key of the table TB_ARA_DOC_ONTOLOGY

ID_ARA_ANAL_DOC is the 1. column of the primary key of the table TB_ARA_DOC_ONTOLOGY

ID_ARA_ANAL_DOC is the 1. column of the primary key of the table TB_ARA_DOC_ONTOLOGY

NB_LINE is the 2. column of the primary key of the table TB_ARA_DOC_ONTOLOGY

NB_LINE is the 2. column of the primary key of the table TB_ARA_DOC_ONTOLOGY

이런식으로 결과가 여러번찍히게 됩니다.

위예제소스로는 순서정보가 다르게 넘어올때는 정렬되지 않는 컬럼정보를 넘겨주게되있더군요.


그래서 기본키컬럼정보및 순서정보를 map으로 넘기게 조금변형햇습니다.

중복된 값이 있기때문에 Set이나 Map등 중복을 허용하지 않는 클래스사용이 좋아보이네요


public static Map<String, Integer> getPrimaryKeyColumnsForTable(Connection connection, String tableName) throws SQLException {

   try(ResultSet pkColumns= connection.getMetaData().getPrimaryKeys(null,null,tableName);) {

    

   Map<String, Integer> pkMap = new HashMap<String, Integer>();

     while(pkColumns.next()) {

       String pkColumnName = pkColumns.getString("COLUMN_NAME");

       Integer pkPosition = pkColumns.getInt("KEY_SEQ");

       

       pkMap.put(pkColumnName, pkPosition);

     }

     return pkMap;

   }

}


컬럼정보와 컬럼의 순서정보를 맵정보로 넘겨주는 예제소스입니다.

예제소스를 그대로 사용하기보다는 개발상황에맞게 예외상황 코드를적절히넣어서 사용하는게 좋아보입니다.

위소스에는 사용한 ResultSet pkColumns 부분을 pkColumns.close시키는부분이나 connection.close부분이없으니

관련 부분은 개발환경에맞게 예외상황처리를해주세요.

예를들면:)

public static Map<String, Integer> getPrimaryKeyColumnsForTable(Connection conn, String tableName) {

ResultSet pkColumns= null;

Map<String, Integer> pkMap = new HashMap<String, Integer>();

try{

pkColumns= conn.getMetaData().getPrimaryKeys(null,null,tableName);

while(pkColumns.next()) {

   String pkColumnName = pkColumns.getString("COLUMN_NAME");

   Integer pkPosition = pkColumns.getInt("KEY_SEQ");

       

  pkMap.put(pkColumnName, pkPosition);

}

}catch( java.sql.SQLException se){

//예외상황 로그남기기 또는 특수처리등


}catch(Exception e){

//기타예외상황 로그남기기 또는 특수처리등

}finally{

try{if(pkColumns!=null)pkColumns.close(); pkColumns=null; }catch(Exception e){}

}

 

 

 

return pkMap;

}

이런식으로 작성하는게 좋을것같네요,


위기능은 jre1.7(jdk1.7)이상부터 지원합니다.