[트러블슈팅] 4. DB 연결 후 Cursor 지정 오류

문정준's avatar
Mar 21, 2025
[트러블슈팅] 4. DB 연결 후 Cursor 지정 오류

1. boolean isThere = rs.next()

Solution

  • rs.next() : 결과 테이블에서 cursor를 한 칸 내린 후, 데이터가 있으면 true, 없으면 false 반환
  • isThere : 데이터가 있는지, 없는지 확인하는 체크형 변수 (rs.next()의 결과값을 받음)
    • rs.next()는 함수이므로 다음 커서를 내릴 수 있으나, isThere로는 동작시킬 수 없음
    • while문에 isThere을 넣을 경우 처음 커서를 내린 값만 계속 유지
      • = while(true)
  • 제대로 작동시키기 위해서는 isThere 값을 반복문 내에서 새로 갱신시켜야 함
  • 코드도 길어지고, 제대로 체크하기 힘듦
    • while(rs.next())로 읽을 수 있을 때만 데이터를 받아오도록 고치는 것이 제일 좋음
import com.mysql.cj.jdbc.Driver; import com.mysql.cj.jdbc.JdbcConnection; import java.sql.*; import java.util.Scanner; public class StoreApp { public static void main(String[] args) { // 1. DB 연결 - 세션 만들어짐 Connection conn = DBConnection.getConnection(); try { // 2. 버퍼 String sql = "select id, name, price, qty from store_tb where id = ?"; PreparedStatement psmt = conn.prepareStatement(sql); psmt.setInt(1, Integer.valueOf(1)); ResultSet rs = psmt.executeQuery(); // 3. Projection int id; String name; int price; int qty; boolean isThere = rs.next(); System.out.println(isThere); // rs.next() : cursor 한 칸 내림 while (isThere) { id = rs.getInt("id"); name = rs.getString("name2"); price = rs.getInt("price"); qty = rs.getInt("qty"); System.out.println(id + " " + name + " " + price + " " + qty); isThere = rs.next(); } } catch (SQLException e) { throw new RuntimeException(e); } } }
 
Share article

sxias