티스토리 뷰

JDBC

페이징 쿼리 이용하기

Programmers 2021. 5. 6. 09:44
반응형

목표: 페이징 쿼리 이용

/* NoticeService.java */
package com.newlecture.app.service;

import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import com.newlecture.app.entity.Notice;
/* CRUD 서비스 목록을 반환하는 함수 */ 
public class NoticeService {
	/* 반복되는 url을 올려서 정의 */
	private String url = "jdbc:oracle:thin:@localhost:1521/XE";
	
	/* 반복되는 id, pwd를 올려서 정의 */
	private String uid = "programmers";
	private String pwd = "111111";
	
	/* 반복되는 Driver를 올려서 정의 */
	private String driver = "oracle.jdbc.driver.OracleDriver";
	
	/*List-> java.util import */
	/*List<Notice>라는 목록으로 반환 */
	public List<Notice> getList(int page) throws ClassNotFoundException, SQLException{
    			//getList()함수를 가지고 반환을 하겠다.
				//List<>라는 컬렉션에 담아서 준다. getlist(int page)로 page값을 받아온다.
		int start = 1 + (page-1)*10 ;	//1, 11, 21, 31, ..
		int end = 10*page;	// 10, 20, 30, ..
		String sql = "SELECT * FROM ( "
				+ "SELECT ROWNUM NUM, N.* FROM ( "
				+ "SELECT * FROM NOTICE ORDER BY REGDATE DESC "
				+ ") N "
				+ ") "
				+ "WHERE NUM BETWEEN ? AND ?";
								//PreparedStatement로 ? ?를 받아와라
		
		
		Class.forName(driver);
		Connection con = DriverManager.getConnection(url, uid, pwd);
		/* PreparedStatement를 설정해서 page 설정*/
		PreparedStatement st = con.prepareStatement(sql);
		st.setInt(1,  start);
		st.setInt(2,  end);
		ResultSet rs = st.executeQuery();
		
		/*반환 하기 위한 목록을 만든다 */
		List<Notice> list = new ArrayList<Notice>();
		
		
		/* Notice를 담을 수있는 그릇이 필요 -> 클래스 추가 entity 이름 Notice.java 추가(그릇, 서비스x)*/
		while(rs.next()) {
			int id = rs.getInt("ID");
			String title = rs.getString("TITLE");
			String writerId = rs.getString("WRITER_ID");
			Date regDate = rs.getDate("REGDATE");
			String content = rs.getString("CONTENT");
			int hit = rs.getInt("hit");
			/*files 추가 */
			String files = rs.getString("FILES");
			
			/*Notice라는 객체를 통해서 notice를 하나 만들면서 초기화하는 생성*/
			Notice notice = new Notice(
					/*Notice.java 생성자와 담을때 딱 맞게 객체를 만들어야 한다. */
					id,
					title,
					writerId,
					regDate,
					content,
					hit,
					files //files 반환값 추가
					);
			/*notice라는 놈을 추가해서 목록에 하나하나 추가 */
			list.add(notice);
			}
				
		rs.close();
		st.close();
		con.close();
		
		return list;
	}

	public int insert(Notice notice) throws ClassNotFoundException, SQLException {
		/*title, writerId, content, files를 정의*/
		/* Notice클래스 내의 함수 호출 */
		String title = notice.getTitle();	
		String writerId =notice.getWriterId();
		String content = notice.getContent();
		String files = notice.getFiles();	//Notice수정해서 files 추가
	
		/*INSERT SQL문 */
		String sql = "INSERT INTO notice ("
				+ "    title,"
				+ "    writer_id,"
				+ "    content,"
				+ "    files"
				+ ") VALUES (?,?,?,?)";	//PreparedStatement를 통한 전달
		
		Class.forName(driver);
		Connection con = DriverManager.getConnection(url, uid, pwd);
		
		/*PreparedStatement도구 사용*/
		PreparedStatement st = con.prepareStatement(sql);	
			//sql문 prepareStatement를 이용해서 st에 저장
		
		/*preparedStatement이용, setString(인덱스값[1부터], 변수)로 저장 */
		st.setString(1, title);
		st.setString(2, writerId);
		st.setString(3, content);
		st.setString(4, files);
		
		/*preparedStatement를 사용 할때에는 sql문을 전달하지 않는다! 이미 전달 되어있다.*/
		int result = st.executeUpdate();
			//excuteUpdate는 int로 실행된 row값을 result에 전달

		st.close();
		con.close();
		
		return result;
	}
	
	public int upate(Notice notice) throws ClassNotFoundException, SQLException {
		/*title, content, files, id를 정의*/
		/* get함수로 변경 */
		String title = notice.getTitle();
		String content = notice.getContent();
		String files = notice.getFiles();
		int id = notice.getId();
	
		/*UPDATE SQL문 */
		String sql = "UPDATE notice "
				+ "SET title=?,"
				+ "    content=?,"
				+ "    files=?"
				+ "WHERE id=?";	//PreparedStatement를 통한 전달
		
		Class.forName(driver);
		Connection con = DriverManager.getConnection(url, uid, pwd);
		
		/*PreparedStatement도구 사용*/
		PreparedStatement st = con.prepareStatement(sql);	
			//sql문 prepareStatement를 이용해서 st에 저장
		
		/*preparedStatement 저장 */
		st.setString(1, title);
		st.setString(2, content);
		st.setString(3, files);
		st.setInt(4, id);	//id는 int형이기 때문에 setInt로 저장
		
		/*preparedStatement를 사용 할때에는 sql문을 전달하지 않는다! 이미 전달 되어있다.*/
		int result = st.executeUpdate();
			//excuteUpdate는 int로 실행된 row값을 result에 전달

		st.close();
		con.close();
		
		return result;
	}
	
	public int delete(int id) throws ClassNotFoundException, SQLException {
	
		/*DELETE SQL문 */
		String sql = "DELETE notice WHERE id=?";	//?:PreparedStatement를 통한 전달
		
		Class.forName(driver);
		Connection con = DriverManager.getConnection(url, uid, pwd);
		
		/*PreparedStatement도구 사용*/
		PreparedStatement st = con.prepareStatement(sql);	
			//sql문 prepareStatement를 이용해서 st에 저장
		
		/*preparedStatement 저장 */
		st.setInt(1, id);	//id는 int형이기 때문에 setInt로 저장
		
		/*preparedStatement를 사용 할때에는 sql문을 전달하지 않는다! 이미 전달 되어있다.*/
		int result = st.executeUpdate();
			//excuteUpdate는 int로 실행된 row값을 result에 전달
				
		st.close();
		con.close();
		
		return result;
	}
}

 

SQL문 삽입 및 PreparedStatement 설정

		int start = 1 + (page-1)*10 ;	//1, 11, 21, 31, ..
		int end = 10*page;	// 10, 20, 30, ..
		String sql = "SELECT * FROM ( "
				+ "SELECT ROWNUM NUM, N.* FROM ( "
				+ "SELECT * FROM NOTICE ORDER BY REGDATE DESC "
				+ ") N "
				+ ") "
				+ "WHERE NUM BETWEEN ? AND ?";
								//PreparedStatement로 ? ?를 받아와라
		
		
		Class.forName(driver);
		Connection con = DriverManager.getConnection(url, uid, pwd);
		/* PreparedStatement를 설정해서 page 설정*/
		PreparedStatement st = con.prepareStatement(sql);
		st.setInt(1,  start);
		st.setInt(2,  end);
		ResultSet rs = st.executeQuery();

page 1 전달

page 2 전달

/* NoticeConsole.java */
package com.newlecture.app.console;

import java.sql.SQLException;
import java.util.List;
import java.util.Scanner;

import com.newlecture.app.entity.Notice;
import com.newlecture.app.service.NoticeService;

public class NoticeConsole {
	
	private NoticeService service;
	
	public NoticeConsole() {
		service = new NoticeService();
	}
	
	/* 내용 UI*/
	public void printNoticeList() throws ClassNotFoundException, SQLException {
		List<Notice> list = service.getList(1);
        				//page값 전달
			
		System.out.println("──────────────────────────────────────");
		System.out.printf("<공지사항> 총 %d 게시글\n", 12);
		System.out.println("──────────────────────────────────────");
		
		for(Notice n : list) {
		System.out.printf("%d. %s / %s / %s\n",
							n.getId(),
							n.getTitle(),
							n.getWriterId(),
							n.getRegDate());
		
		}
		System.out.println("──────────────────────────────────────");
		System.out.printf("         %d/%d pages \n", 1, 2);
		
		
	}

	/* 메뉴 UI*/
	public int inputNoticeMenu() {
		Scanner scan = new Scanner(System.in);
		
		System.out.printf("1. 상세조회/ 2.이전/ 3.다음/ 4.글쓰기 / 5.종료 >");
		String menu_ = scan.nextLine();
		int menu = Integer.parseInt(menu_);
		
		return menu;
	}
}

 

반응형
댓글
공지사항