11.검색서비스 메뉴및 추가하기
검색서비스 메뉴 및 추가 하기
1.검색서비스 메뉴 만들기
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;
private int page;
private Object searchWord; //클래스에 멤버변수로 들어간다
public Noticeconsole() {
service = new NoticeService();
page=1;
String searchField = "";
searchWord="";
}
public void printNoticeList() throws ClassNotFoundException, SQLException {
List<Notice> list = service.getList(page); // 페이지 1 넣어보기
int count = service.getcount(); // 목록을 출력하고자하면 얻어와야한다
int lastPage = count/10; // 만약 레코드가 100이면 10 페이지 이지만 93 일경우 나머지 발생
//현재 페이지목록을 구하고 전체 갯수를 구해서 마지막 페이지를 구한다
lastPage = count%10>0?lastPage+1:lastPage;
// 나머지 발생할 경우 생각 해줘야한다
System.out.println("----------------------------");
System.out.printf("<공지사항> 총%d게시글\n",count);
System.out.println("----------------------------");
for(Notice n :list) {
System.out.printf("%d. %s / %s / %s\n",
n.getId(),
n.getTitle(),
n.getWriterld(),
n.getRegDate());
}
System.out.println("----------------------------");
System.out.printf(" %d%d pages\n", page, lastPage);
}
public int inputNoticeMenu() {
Scanner scan = new Scanner(System.in);
System.out.printf("1.상세조회/2.이전/3.다음/4.글쓰기/5.검색/6.종료>");
String menu_ = scan.nextLine();// 정수가 아닌 다른 것이 눌렸을 경우 에러가 발생한다 다음입력에 영향을 줄 수 있다
// 메뉴를 임시변수에다가 담는다
int menu = Integer.parseInt(menu_); // 메뉴를 정수형으로 바꾼다
return menu;
}
public void movePrevList() {
if(page == 1) {
System.out.println("==============");
System.out.println("이전페이지가 없습니다");
System.out.println("==============");
return;
}
page --;
}
public void moveNextList() throws ClassNotFoundException, SQLException {
int count = service.getcount(); // 이전에 사용했던것을 쓰면 안된다 (위의것)
int lastPage = count/10;
lastPage = count%10>0?lastPage+1:lastPage;
if(page == lastPage) { // 마지막번호는 movenextlist 가 호출될떄 가져와서 있는지 없는지 학인해얃한다
System.out.println("다음페이지가 없습니다");
return;
}
page++;
}
public void inputSearchWord() {
Scanner scan = new Scanner(System.in);//멤버에다가 둬야 다른 것과 공유한다 공유해야할것만 둔다
//검색할때 검색어도 중요하지만 필드로 검색할건지 작성자로 검색할건지 있을 수도 있다
System.out.println("검색범주( title/content/writerld)중에 하나를 입력하세요");
System.out.println(">");
String searchField = scan.nextLine();
System.out.println("검색어>");
searchWord = scan.nextLine();
// 목록을 조회할때 pringNoticeList()가 쓸 내용이다-공유해야한다 멤버변수
}
}
- 검색서비스 추가하기
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;
private int page;
private String searchWord; //클래스에 멤버변수로 들어간다
private String searchField;
public Noticeconsole() {
service = new NoticeService();
page=1;
searchField = "TITLE";
searchWord="";
}
public void printNoticeList() throws ClassNotFoundException, SQLException {
List<Notice> list = service.getList(page, searchField , searchWord); // 페이지 1 넣어보기
int count = service.getcount(); // 목록을 출력하고자하면 얻어와야한다
int lastPage = count/10; // 만약 레코드가 100이면 10 페이지 이지만 93 일경우 나머지 발생
//현재 페이지목록을 구하고 전체 갯수를 구해서 마지막 페이지를 구한다
lastPage = count%10>0?lastPage+1:lastPage;
// 나머지 발생할 경우 생각 해줘야한다
System.out.println("----------------------------");
System.out.printf("<공지사항> 총%d게시글\n",count);
System.out.println("----------------------------");
for(Notice n :list) {
System.out.printf("%d. %s / %s / %s\n",
n.getId(),
n.getTitle(),
n.getWriterld(),
n.getRegDate());
}
System.out.println("----------------------------");
System.out.printf(" %d%d pages\n", page, lastPage);
}
public int inputNoticeMenu() {
Scanner scan = new Scanner(System.in);
System.out.printf("1.상세조회/2.이전/3.다음/4.글쓰기/5.검색/6.종료>");
String menu_ = scan.nextLine();// 정수가 아닌 다른 것이 눌렸을 경우 에러가 발생한다 다음입력에 영향을 줄 수 있다
// 메뉴를 임시변수에다가 담는다
int menu = Integer.parseInt(menu_); // 메뉴를 정수형으로 바꾼다
return menu;
}
public void movePrevList() {
if(page == 1) {
System.out.println("==============");
System.out.println("이전페이지가 없습니다");
System.out.println("==============");
return;
}
page --;
}
public void moveNextList() throws ClassNotFoundException, SQLException {
int count = service.getcount(); // 이전에 사용했던것을 쓰면 안된다 (위의것)
int lastPage = count/10;
lastPage = count%10>0?lastPage+1:lastPage;
if(page == lastPage) { // 마지막번호는 movenextlist 가 호출될떄 가져와서 있는지 없는지 학인해얃한다
System.out.println("다음페이지가 없습니다");
return;
}
page++;
}
public void inputSearchWord() {
Scanner scan = new Scanner(System.in);//멤버에다가 둬야 다른 것과 공유한다 공유해야할것만 둔다
//검색할때 검색어도 중요하지만 필드로 검색할건지 작성자로 검색할건지 있을 수도 있다
System.out.println("검색범주( title/content/writerld)중에 하나를 입력하세요");
System.out.println(">");
searchField = scan.nextLine();
System.out.println("검색어>");
searchWord = scan.nextLine();
// 목록을 조회할때 pringNoticeList()가 쓸 내용이다-공유해야한다 멤버변수
}
}
package com.newlecture.app.service;
import java.beans.Statement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.newlecture.app.entity.Notice;
public class NoticeService {
String url ="jdbc:oracle:thin:@localhost:1521/orcl";
private String uid ="eunji";
private String pwd="1234";
// 서비스 클래스에서 목록을 보는 리스트-검색을 하려면 사용자가 두가지 정보를 제공할때
//검색을 하는 기준값(제목으로 아니면 작성자 아이디로,컨텐트로)- field에 저장/ 검색어-> query에저장해서 넘긴다
public List<Notice> getList(int page, String field, String query) throws ClassNotFoundException, SQLException{
int start = 1; // 1,11,21,31
int end = 10* page; //10,20,30,40
String sql = "SELECT*FROM NOTICE_VIEW WHERE "+field+" LIKE ? AND NUM BETWEEN ? AND?";
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection(url,uid,pwd);
PreparedStatement st =con.prepareStatement(sql); // 여기서 sql을 먼저 전달하기 때문에
st.setString(1, "%"+query+"%"); // like 뒤에 %A%를 넣어주기
st.setInt(2, start); // 순위가 밀려서 2,3 이된다
st.setInt(3, end);
ResultSet rs = st.executeQuery();// 여기의 sql을 삭제
List<Notice> list = new ArrayList<Notice>();
// notice라는 그릇이 필요하다
while(rs.next()) {
int id = rs.getInt("ID");
String title = rs.getString("TITLE");
String writerld = rs.getString("WRITER_ID");
String content = rs.getString("CONTENT");
Date regDate=rs.getDate("REGDATE");
int hit = rs.getInt("hit");
String files = rs.getString("FILES");
Notice notice = new Notice( // 반환하는 녀석들~
id,
title,
writerld,
content,
regDate,
hit,
files
);
//notice를 add해서 추가하게되면 목록에 하나하나씩 출력하게된다
list.add(notice);
}
rs.close();
st.close();
con.close();
return list;
}
// 단일값을 얻어오는 것 scalar
public int getcount() throws ClassNotFoundException, SQLException {
int count = 0;
String sql = "select count (id) count from NOTICE";
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection(url,uid,pwd);
java.sql.Statement st =con.createStatement();
ResultSet rs = st.executeQuery(sql);
// resultset으로 받는것은 단일값 하나로 가지는 레코드를 가진다
// 값을 꺼낼때는 그 결과집합에 대한 컬럼을 가져오게되는데 실행하면 컬럼명이 count(id)로 나오게 된다
// 별칭을 줘야한다 select count (id) count from NOTICE;
if(rs.next())
//위 처럼 id에 별칭을 주므로 count를 id로 쓸 수있다
count = rs.getInt("count");
rs.close();
st.close();
con.close();
return count;
}
public int insert(Notice notice) throws ClassNotFoundException, SQLException {
String title = notice.getTitle();
String writerId =notice.getWriterld();
String content = notice.getContent();
String files = notice.getFiles();
String url ="jdbc:oracle:thin:@localhost:1521/orcl";
String sql = "INSERT INTO notice ("
+ " title,"
+ " writer_id,"
+ " content,"
+ " files"
+ ") VALUES (?,?,?,?)";
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection(url,uid,pwd);
// sql.Statement st =con.createStatement();
//st.execute query,update를 실행 할때 넘겼는데
PreparedStatement st=con.prepareStatement(sql); //prepare 미리 준비해서 실행하라 statement자체가 쿼리문을 가지고 있다
st.setString(1, title);
st.setString(2, writerId);
st.setString(3, content);
st.setString(4, files);
//prepare쓸때는 sql을 쓰면 안된다
int result = st.executeUpdate();
// System.out.println(result); 출력되는 문장은 지워도 된다
st.close();
con.close();
return result;
}
public int update(Notice notice) throws SQLException, ClassNotFoundException {
String title = notice.getTitle();
String content = notice.getContent();
String files =notice.getFiles();
int id = notice.getId();
String sql = "UPDATE notice "
+ "SET" // 덧셈으 하고 나면은 결과가 notice set이 되므로 결과가
+ " title = ?,"
+ " content=?,"
+ " files = ?"
+ "WHERE id =?";
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection(url,uid,pwd);
PreparedStatement st=con.prepareStatement(sql);
st.setString(1, title);
st.setString(2, content);
st.setString(3, files);
st.setInt(4, id);
//prepare쓸때는 sql을 쓰면 안된다
int result = st.executeUpdate();
st.close();
con.close();
return result;
}
public int delete(int id) throws SQLException, ClassNotFoundException {
// int id = 3; 인자로 받기 때문에 지워준다
String url ="jdbc:oracle:thin:@localhost:1521/orcl";
String sql = "DELETE NOTICE WHERE ID=?";
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection(url,uid,pwd);
// sql.Statement st =con.createStatement();
//st.execute query,update를 실행 할때 넘겼는데
PreparedStatement st=con.prepareStatement(sql); //prepare 미리 준비해서 실행하라 statement자체가 쿼리문을 가지고 있다
st.setInt(1, id);
//prepare쓸때는 sql을 쓰면 안된다
int result = st.executeUpdate();
st.close();
con.close();
return result;
}
}
댓글남기기