티스토리 뷰

Programming/JDBC

[JDBC] Select 문 실행

Allg 2017. 6. 26. 16:12


Select 문 실행

1. JDBC 드라이버를 로딩

  • Class.forName(“com.mysql.jdbc.Driver”)

2. Connection 객체를 생성

  • con = DriverManager.getConnection(url, user, pw)

3. Statement 객체를 생성

  • Staement - SQL문을 데이터베이스에 보내기위한 객체입니다.
  • stmt = con.createStatement()

4. SQL 문장을 실행

  • SQL 문장을 실행하고 결과를 ResultSet으로 리턴합니다.
  • stmt.excuteQuery(“SELECT * FROM customers”);

5. ResultSet에 저장된 데이터 얻는 방법

  • ResultSet - SQL 질의에 의해 생성된 테이블을 저장하는 객체입니다.
  • rs = stmt.excuteQuery(SQL) - SQL 질의 결과를 ResultSet에 저장합니다.
  • rs.next() 를 이용해서 커서를 이동합니다.
  • 결과가 1 개인 경우
    if(rs.next()) { }

  • 결과가 2개 이상인 경우
    while(rs.next()) { }

  • rs.getString(“컬럼”) - ex) rs.getString(“id”)

  • rs.getInt(컬럼순번) - ex) rs.getInt(1)
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class Select {

    public static void main(String[] args) {

        Connection con = null;                 // 데이터 베이스와 연결을 위한 객체
        Statement stmt = null;                 // SQL 문을 데이터베이스에 보내기위한 객체
        ResultSet rs = null;                   // SQL 질의에 의해 생성된 테이블을 저장하는 객체

        // 1. JDBC Driver Class - com.mysql.jdbc.Driver
        String driver = "com.mysql.jdbc.Driver";

        // 2. 데이터베이스에 연결하기 위한 정보
        String url = "jdbc:mysql://localhost:3306/test_db";       // 연결문자열
        String user = "root";                                     // 데이터베이스 ID
        String pw = "1234";                                       // 데이터베이스 PW

        String SQL = "SELECT * FROM customers";

        try {
            // 1. JDBC 드라이버 로딩
            Class.forName(driver);

            // 2. Connection 객체 생성
            con = DriverManager.getConnection(url, user, pw); // DB 연결

            // 3. Statement 객체 생성
            stmt = con.createStatement();

            // 4. SQL 문장을 실행하고 결과를 리턴
            // stmt.excuteQuery(SQL) : select
            // stmt.excuteUpdate(SQL) : insert, update, delete ..
            rs = stmt.executeQuery(SQL);

            // 5. ResultSet에 저장된 데이터 얻기 - 결과가 2개 이상
            while (rs.next()) {

                String id = rs.getString("id");
                String pass = rs.getString("pass");
                String name = rs.getString("name");
                String phone = rs.getString("phone");
                String email = rs.getString(5); //rs.getString("email");

                System.out.println(id + " " + pass + " " + name + " " + phone + " " + email);
            }

            //5. ResultSet에 저장된 데이터 얻기 - 결과가 1개
            // if(rs.next()) {
            //
            // }
            // else {
            //
            // }
        } catch (SQLException e) {

            System.out.println("SQL Error : " + e.getMessage());

        } catch (ClassNotFoundException e1) {

            System.out.println("[JDBC Connector Driver 오류 : " + e1.getMessage() + "]");

        } finally {

            //사용순서와 반대로 close 함
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (stmt != null) {
                try {
                    stmt.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

            if (con != null) {
                try {
                    con.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}


'Programming > JDBC' 카테고리의 다른 글

[JDBC] DAO  (2) 2017.07.03
[JDBC] Delete 문 실행  (0) 2017.06.30
[JDBC] Update 문 실행  (2) 2017.06.30
[JDBC] Insert 문 실행  (0) 2017.06.27
[JDBC] JDBC 드라이버 로딩과 Connection 생성  (3) 2017.06.26
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
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
글 보관함