본문 바로가기
Language/JAVA

JDBC , DB , try-with-resources (Java 1.7이상) 자원해제

by javapp 자바앱 2020. 6. 1.
728x90

 

https://blog.naver.com/pgram16/221821654060

 

try-with-resource : 자원 해제하기

jdk7부터 try-with-resource로 기존에 사용하던 try-catch-finally 문을 이용해 자원을 해제하던 것을 더 ...

blog.naver.com

 

https://blog.naver.com/nature128/221430455866

 

try-with-resources (Java 1.7이상)

//Java 7 부터는 Try문 안에 리소스를 선언하면 자동으로 리소스 관리// ★ Connection이나 PreparedS...

blog.naver.com

 


 

               try {

                      Class.forName(driver);

               } catch (ClassNotFoundException e2) {

                      e2.printStackTrace();

               }

               try(  

                      Connection con = DriverManager.getConnection(url, user, pw);

                      Statement stmt = con.createStatement();

                      ResultSet rs = stmt.executeQuery("SELECT * FROM board");

                      PreparedStatement pstmt = con.prepareStatement(preQuery);

                  ) //try() 안에 넣기

               {

                     

                      System.out.println("연결 성공");

                      while(rs.next()) {

                              String id = rs.getString("id");

                              String title = rs.getString("title");

                              String writer = rs.getString("writer");

                              String contents = rs.getString("contents");

                              LocalDateTime regdate = rs.getTimestamp("regdate").toLocalDateTime();

                             

                              System.out.printf("%s | %s | %s | %s | %s \n", id,title,writer,contents,regdate.toString());

                              System.out.println("-------------------------------------");

                      }

                      System.out.println("Insert using PreparedStatement");

                     

                      pstmt.setString(1, "have a nice day");

                      pstmt.setString(2, "yoon");

                      pstmt.setString(3, "Good luck");                                 

                      pstmt.setTimestamp(4, Timestamp.valueOf(LocalDateTime.now()));

                      pstmt.setString(5, "0");

                      pstmt.executeUpdate();

               } catch (SQLException e) {

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

               }

댓글