본문 바로가기

Learning/SQL

JDBC SELECT

<JDBC SELECT>

 

 

 

1
2
3
SELECT * FROM NAMECARD
ORDER BY NO;
commit;
cs

 

 

 


 

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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package com.oracle.namecardTest;
 
import java.sql.*//자바 sql 라이브러리 
 
public class Select {
 
    public static void main(String[] args) {
        //(oracle) jdbc:oracle:thin:@localhost:1521:xe
        //(mySQL) jdbc:mysql://localhost:3306/db이름
//        미리 입력할 오라클 주소, 계정, 비밀번호를 변수로 저장
        String DB_URL = "jdbc:oracle:thin:@127.0.0.1:1521:XE";
        String DB_USER = "scott";
        String DB_PASSWORD = "1234";
//      conn은 오라클 연결을 위한 객체
        Connection conn = null;
//      stmt는 sql문을 실행하기 위한 객체
        Statement stmt = null;
//      rs는 sql문 실행 후 결과값을 받아오는 객체
//      select절이 실행되었을때 출력되는 값이 있기 때문에 rs객체 필요
        ResultSet rs = null
 
        String query = "SELECT * FROM NAMECARD ORDER BY NO";
        
        
        try {
            //1. 오라클 드라이버 로딩   ( ojdbc6_g.jar )            
            Class.forName("oracle.jdbc.driver.OracleDriver");
        } catch (ClassNotFoundException e ) { //클래스를 못찾았을때 (드라이버 없을때 )
            e.printStackTrace();
        }
 
        try { //DB 연결 부분은 try-catch 문으로 예외 발생시 처리
            //2. DB 연결
            conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
            //3. SQL 문 준비
            stmt = conn.createStatement();
            //4. SQL 쿼리 실행 하고 rs에 테이블데이터를 받아옴
            rs=stmt.executeQuery(query);
            
            while(rs.next()) {
                int no = rs.getInt("no");
                String name = rs.getString("name");
                String mobile = rs.getString("mobile");
                String email = rs.getString("email");
                String company = rs.getString("company");
                System.out.println(no+"|"+name+"|"+mobile+"|"+
                        email+"|"+company);
            }
            
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                rs.close();
                stmt.close();        //State문 닫기
                conn.close();
            } catch (SQLException e) {}
        }
    }
 
}
 

'Learning > SQL' 카테고리의 다른 글

namecard 완성하기  (0) 2020.06.24
PreparedStatement  (0) 2020.06.23
JDBC INSERT  (0) 2020.06.23
JDBC Test  (0) 2020.06.23
DCL: 데이터 제어어  (0) 2020.06.23