import java.sql.Connection;
import java.sql.Statement;
import java.sql.*;

public class MetadataTest {
       
        String url = "jdbc:oracle:thin:@192.168.2.22:1521:ora9i";
        String query = "SELECT * FROM SCOTT.EMP";
        Connection con = null;
        Statement stmt = null;
       
        public void metadataTest()
        {
                try
                {
                        Class.forName("oracle.jdbc.driver.OracleDriver");
                }catch(java.lang.ClassNotFoundException e)
                {
                        System.err.print("ClassNotFoundException : " + e.getMessage());
                }
               
                try
                {
                        con = DriverManager.getConnection(url, "scott", "tiger");
                        System.out.println("Connected to DB ............");
                        stmt = con.createStatement();
                        ResultSet rs = stmt.executeQuery(query);
                        // 테이블의 메타데이타 정보를 구성하여 ResultSetMetaData 에 저장  
                        ResultSetMetaData rsmd = rs.getMetaData();
                       
                        int numberOfColumn = rsmd.getColumnCount();
                       
                        System.out.println("============================================================");
                        System.out.println("Number of Columns : " + numberOfColumn);
                        System.out.println("============================================================");
                        System.out.println("Column Name  |  JDBC type  |  Null Allowed  |  Read Only    ");
                        System.out.println("============================================================");
                       
                        for(int i = 1; i <= numberOfColumn; i++)
                        {
                                String columnName = rsmd.getColumnName(i);// 필드명
                                String jdbcType = rsmd.getColumnTypeName(i);// 필드 속성
                                int isNull = rsmd.isNullable(i); // 필드 Null 허용여부
                                int jdbcLength = rsmd.getPrecision(i); // 컬럼 length
                                boolean rOnly = rsmd.isReadOnly(i); // 읽기 전용 여부
                               
                                System.out.print(columnName);// 필드 명을 출력
                               
                                for(int j = 0; (columnName.length() + j) < 12; j++)
                                {
                                        System.out.print(" ");
                                }
                                System.out.print("     " + jdbcType + "(" + jdbcLength + ")"); // 필드의 타입을 출력
                                for(int j = 0; (jdbcType.length() + j) < 12; j++)
                                {
                                        System.out.print(" ");
                                }
                                if(isNull == 0)// 필드의 Null 허용 여부 출력
                                {
                                        System.out.print("  Not Null ");
                                }else if(isNull == 1)
                                {
                                        System.out.print("   Null    ");
                                }else
                                {
                                        System.out.print("   Unknown ");
                                }
                               
                                System.out.println("         " + rOnly);// 읽기 전용 여부 출력
                        }
                        stmt.close();
                        con.close();
                        System.out.println("Disconnected From DB ..........");
                       
                }catch(SQLException e)
                {
                        System.err.print("SQLException : " + e.getMessage());
                }
        }
        public static void main(String[] arr)
        {
                new MetadataTest().metadataTest();
        }
}

/*
출력 결과 :
Connected to DB ............
============================================================
Number of Columns : 8
============================================================
Column Name  |  JDBC type  |  Null Allowed  |  Read Only    
============================================================
EMPNO            NUMBER(4)        Not Null          false
ENAME            VARCHAR2(10)       Null             false
JOB              VARCHAR2(9)       Null             false
MGR              NUMBER(4)         Null             false
HIREDATE         DATE(0)           Null             false
SAL              NUMBER(7)         Null             false
COMM             NUMBER(7)         Null             false
DEPTNO           NUMBER(2)         Null             false
Disconnected From DB ..........
*/
02 5, 2009 17:50 02 5, 2009 17:50

Trackback URL : http://develop.sunshiny.co.kr/trackback/105

Leave a comment


# 컬럼들에 대한 정보가 미리 확실하게 주어지지 못한 상태에서 특정 테이블의 정보와 데이터를 가져올수 있다.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;

public class MetaDataDynamic {

        Connection con = null;
        Statement stmt = null;

        public void connectionMethod()
        {              
                String url = "jdbc:oracle:thin:@192.168.2.22:1521:ora9i";
                String username = "scott";
                String passwd = "tiger";
                String query = "SELECT * FROM SCOTT.DEPT";
               
                metaDataDynamic(url, username, passwd, query);
        }
       
        public void metaDataDynamic(String url, String username, String passwd, String query)
        {
                Connection conn = null;
                Statement stmt = null;
                ResultSet rs = null;
                ResultSetMetaData rsmd = null;
               
                try
                {
                        Class.forName("oracle.jdbc.driver.OracleDriver");
                }catch(ClassNotFoundException e)
                {
                        System.err.println("ClassNotFoundException : " + e.getMessage());
                        System.exit(-1);
                }
               
                try
                {
                        conn = DriverManager.getConnection(url, username, passwd);
                        stmt = conn.createStatement();
                       
                        System.out.println("Connected to DB .........");
                        System.out.println(" ");
                       
                        rs = stmt.executeQuery(query);
                        rsmd = rs.getMetaData();
                        int numberOfCount = rsmd.getColumnCount();
                        String[] columnLabel = new String[numberOfCount];
                        String[] columnType = new String[numberOfCount];
                        String[] columnValue = new String[numberOfCount];
                       
                        for(int i = 0; i < numberOfCount; i++)
                        {
                                columnLabel[i] = rsmd.getColumnLabel(i+1);
                                columnType[i] = rsmd.getColumnTypeName(i+1);
                        }
                       
                        while(rs.next())
                        {
                                for(int j = 0; j < numberOfCount; j++)
                                {
                                        if(columnType[j].compareTo("VARCHAR2") == 0)
                                        {
                                                columnValue[j] = rs.getString(j+1);
                                        }else if(columnType[j].compareTo("NUMBER") == 0)
                                        {
                                                columnValue[j] = Integer.toString(rs.getInt(j+1));
                                        }
                                }
                               
                                for(int j = 0; j < numberOfCount; j++)
                                {// 컬럼명과 컬럼에 저장된 값을 출력
                                        System.out.println(columnLabel[j] + " : " + columnValue[j]);
                                }
                                System.out.println("============================================");
                        }
                        stmt.close();
                        conn.close();
                       
                        System.out.println(" ");
                        System.out.println("Disconnected from DB ............");
                }catch(SQLException e)
                {
                        System.err.println("SQLException : " + e.getMessage());
                        System.exit(-1);
                }
        }
       
        public static void main(String[] arr)
        {
                new MetaDataDynamic().connectionMethod();
        }
}

/*
출력 결과 :
Connected to DB .........
 
DEPTNO : 10
DNAME : ACCOUNTING
LOC : NEW YORK
============================================
DEPTNO : 20
DNAME : RESEARCH
LOC : DALLAS
============================================
DEPTNO : 30
DNAME : SALES
LOC : CHICAGO
============================================
DEPTNO : 40
DNAME : OPERATIONS
LOC : BOSTON
============================================
 
Disconnected from DB ............
*/
02 5, 2009 17:50 02 5, 2009 17:50

Trackback URL : http://develop.sunshiny.co.kr/trackback/106

Leave a comment


Recent Posts

  1. Linux - Telnet 서비스 비활성및 실행
  2. NT - 서버 원격데스크탑 연결
  3. NT - http와 https간에 세션 공유가...
  4. Unix - 대량 파일 이동, 삭제시 Argu...
  5. Oracle - SYS_CONTEXT 함수를 이용하...

Recent Comments

  1. 네. 고맙습니다^^ 행복한 한해 보... sunshiny 01 16,
  2. sunshiny님. 안녕하세요... 올려 주... yihans 01 16,
  3. 답글 주셔서 고맙습니다^^ 소스 복... sunshiny 01 11,
  4. 관리자만 볼 수 있는 댓글입니다. 비밀방문자 01 11,
  5. 넵 답변감사합니다^^ 좋은 하루 되... 노로링

Recent Trackbacks

  1. 윈도우 cmd 명령어 팁 월풍도원(月風道院) - Delight on th... %M
  2. 파일 압축 Like RadioHead %M
  3. Mysql - mysql 설치후 Character set... 멀고 가까움이 다르기 때문 %M

Calendar

«   02 2012   »
      1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29      

Bookmarks

  1. 위키피디아
  2. MysqlKorea
  3. Oracle All Documentation
  4. 엑셈
  5. 오라클 클럽
  6. 네이버개발자센터
  7. API - Java
  8. API - Spring
  9. Java Community
  10. Reference - Spring
  11. 스프링사용자
  12. 자바지기
  13. Ready System
  14. Solaris Freeware
  15. Linux-Site
  16. RedHat Korea
  17. 윈디하나의 솔라나라

Site Stats

TOTAL 217714 HIT
TODAY 16 HIT
YESTERDAY 115 HIT