ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Consumer 인터페이스를 사용해 DB연결하기(+ try-with-resources , 람다 )
    JAVA/스트림, 컬렉션 프레임워크, 람다 2024. 6. 20. 12:18

    ▤ 목차

       

       

       

      ✔DB와 연결하기

      우선 db와 연동할 것이기에 mariadb 파일을 build path를 해준 후 진행하자.

       

      💻 코드로 보기

      public class MyLambda5Db {
      
      	public MyLambda5Db() {
      		//db연결
      		try {
      			Class.forName("org.mariadb.jdbc.Driver");
      		} catch (Exception e) {
      			System.out.println("Driver loding fail : " + e);
      			return;
      		}
              
              //메서드 호출 (람다 사용)
      		queryTable("select * from sangdata", rs -> {
      			try {
      				while (rs.next()) {
      					System.out.println(rs.getString("code") + " " + rs.getString("sang") + " " + rs.getString("su")
      							+ " " + rs.getString("dan") + " ");
      				}
      			} catch (Exception e) {
      				System.out.println("err : " + e);
      			}
      		});
      
      	}
      
      	private void queryTable(String sql, Consumer<ResultSet> consumer) {
      		//try는 매개변수를 가질 수 있다. try with resources 문법에 준함
      		try (Connection conn= DriverManager.getConnection("jdbc:mariadb://localhost:3306/test","root","123");
      			PreparedStatement pstmt = conn.prepareStatement(sql);
      			ResultSet rs = pstmt.executeQuery()){
      			consumer.accept(rs);
      			
      			rs.close();
      			pstmt.close();
      			conn.close();
      		} catch (Exception e) {
      			System.out.println("queryTable err: " + e);
      		}
      	}
      
      	public static void main(String[] args) {
      		new MyLambda5Db();
      
      	}
      
      }

       

       

       

       

       


       

       

      ✔ 코드 흐름보기

      위의 코드는 어떤 방식으로 흘러갈까?

      디버깅을 할 수 있지만 찍어보자.

       

      💻 코드로 보기

      public class MyLambda5Db {
      
      	public MyLambda5Db() {
      		//db연결
      		try {
      			Class.forName("org.mariadb.jdbc.Driver");
      		} catch (Exception e) {
      			System.out.println("Driver loding fail : " + e);
      			return;
      		}
              
              //메서드 호출 (람다 사용)
      		queryTable("select * from sangdata", rs -> {
              System.out.println("처리2");
      			try {
      				while (rs.next()) {
      					System.out.println(rs.getString("code") + " " + rs.getString("sang") + " " + rs.getString("su")
      							+ " " + rs.getString("dan") + " ");
      				}
      			} catch (Exception e) {
      				System.out.println("err : " + e);
      			}
      		});
      
      	}
      
      	private void queryTable(String sql, Consumer<ResultSet> consumer) {
      		//try는 매개변수를 가질 수 있다. try with resources 문법에 준함
      		try (Connection conn= DriverManager.getConnection("jdbc:mariadb://localhost:3306/test","root","123");
      			PreparedStatement pstmt = conn.prepareStatement(sql);
      			ResultSet rs = pstmt.executeQuery()){
                  System.out.println("처리1");
      			consumer.accept(rs);
      			System.out.println("처리3");
      			rs.close();
      			pstmt.close();
      			conn.close();
      		} catch (Exception e) {
      			System.out.println("queryTable err: " + e);
      		}
      	}
      
      	public static void main(String[] args) {
      		new MyLambda5Db();
      
      	}
      
      }

       

      위와 같은 방식으로 처리된다. 람다로 코드가 줄어든다는 장점이 있다. 가독성이 떨이지는것 같기도..

       

       

       

       

      👏 try-with-resources

      try문에는 try-catch-finally문이 있고 try-with-resources문이 있다.

      resources란? 보통 외부 데이터(DB,File,Network)를 일컫는다.

      외부데이터를 열거나 할당하고나서 닫아주기(close() 사용)위해 finally문을 사용 사용한 적이 있을 것이다.

      try {
      	...
      } cacth (){
      	...
      } finally {
      	try{
          	~.close();
              ~.close();
          } cacth(){
          	...
          }
       };

      하지만 단순히 자원을 반납하기위해서 코드가 늘어진다.

      다른 에러나 조건이 들어간다면 반납을 위한 코드가 길어진다. 코드가 필요 이상으로 길어지게 된다.

      이런 경우를 위해 자동으로 반납할 수 있도록 try resources문이 나왔다.

       

      try(파일을 열거나 자원을 할당하는 명령문){...}

      위와 같은 형태로 이루어져있다.

      try 블록이 끝나자마자 자동으로 파일을 닫거나 할당된 자원을 해제해준다.

       

      🔶 AutoCloseable 인터페이스

      try- resources 문에서 사용할 수 있는 클래스의 조건이 있는데,

      바로 AutoCloseable 인터페이스를 구현받은 클래스여야한다는 점이다.

      그럼, 자동으로 자원을 close해준다.

       

      위의 코드에서 7번 과정은 불필요하게 된다.

       

       

       

      [+TMI ]

       

      우연히 발견한 재밌는 블로그를 찾았다.

      https://multifrontgarden.tistory.com/192

       

       

      😊정리

      try는 매개변수를 가질 수 있다. 파일을 열거나 자원을 반납을 해주기때문에

      이를 위한 불필요한 코드가 길어지는 일을 방지할 수 있다.

    Designed by Tistory.