๐Ÿ“– JDBC ( Java Database Connectivity)

๐Ÿ”Œ ์ž๋ฐ”์™€ ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค์˜ ์—ฐ๋™

  1. ๋“œ๋ผ์ด๋ฒ„ ๋กœ๋”ฉ (JDBC Load)
    • Class.forName(“๋“œ๋ผ์ด๋ฒ„ Path”)
      • Class ํด๋ž˜์Šค๊ฐ€ ํด๋ž˜์Šค์˜ ์ •๋ณด(ํ•„๋“œ, ๋ฉ”์„œ๋“œ ํด๋ž˜์Šค์˜ ์ข…๋ฅ˜)๋ฅผ ๋‹ด๋Š” ๋ฉ”ํƒ€ ํด๋ž˜์Šค์ด๊ณ  JVM์€ ํ•ด๋‹น ํด๋ž˜์Šค์˜ ์ •๋ณด๋ฅผ ๋กœ๋“œํ•œ๋‹ค.
  2. DB ์—ฐ๊ฒฐ Connection
    • DriverManager.getConnection(url, ID, PWD)
      • Connection ๊ฐ์ฒด๋ฅผ ์ƒ์„ฑํ•œํ›„
      • DriverManager์—์„œ ์‹œ์Šคํ…œ ํ”„๋กœํผํ‹ฐ “jdbc.drivers"์— ์ฐธ์กฐ๋œ ๋“œ๋ผ์ด๋ฒ„ ํด๋ž˜์Šค๋ฅผ ๋กœ๋“œํ•œ๋‹ค.
      • ์ดํ›„ Connection ๊ฐ์ฒด์— ํ• ๋‹น
  3. ์ฟผ๋ฆฌ ์ƒ์„ฑ ๋ฐ ์งˆ์˜
    
    PreparedStatement psmt = null;
    psmt = conn.prepareStatement("SQL๋ฌธ");
    
    
    Statement stmt = null;
    stmt = conn.createStatement("SQL๋ฌธ");
    

    โœ”๏ธ PreparedStatement`๋Š” ์ฟผ๋ฆฌ์— ?๋กœ ๋งค๊ฐœ๋ณ€์ˆ˜๋ฅผ ๋ฐ›์•„ ์‹คํ–‰ ๊ฐ€๋Šฅ

  4. ์ฟผ๋ฆฌ ์‹คํ–‰
    • psmt.executeUpdate()
      • INSERT UPDATE DELETE ๊ฐ™์€ ๊ฐ’์„ ๋ฐ›์•„์˜ค์ง€ ์•Š๋Š” ์ฟผ๋ฆฌ๋ฌธ์€ psmt.executeUpdate()๋กœ ์‹คํ–‰
    • psmt.executeQuery()
      • SELECT ์ฒ˜๋Ÿผ ๊ฒฐ๊ณผ ํ…Œ์ด๋ธ”์ด ํ•„์š”ํ•œ ์ฟผ๋ฆฌ๋ฌธ์€ ์ฟผ๋ฆฌ ์‹คํ–‰ ์ด์ „์— ResultSet๊ฐ์ฒด๋ฅผ ์ƒ์„ฑํ•œํ›„ psmt.executeQuery()๋ฅผ ํ• ๋‹นํ•œ๋‹ค.
  5. ResultSet ์ฒ˜๋ฆฌ
    while(rs.next()) {
        int i=1;
        int id = rs.getInt(i++);
        String name = rs.getString(i++);
        String addr = rs.getString(i++);
     }
    

    `

  1. Close()
    if (rs!=null) {
       try {
          rs.close();
       } catch (SQLException e) {
       }
    }
    
    if(stmt!=null) {
       try {
          stmt.close();
       } catch (SQLException e) {
       }
    }
    
    if(conn!=null) {
       try {
          conn.close();
       } catch (SQLException e) {
       }
    }
    

    ` โœ”๏ธ Openํ•œ ๊ฐ์ฒด๋“ค์˜ ์—ญ์ˆœ์œผ๋กœ close ์‹œํ‚จ๋‹ค.