-
[JDBC] singletonDataBase/JDBC 2022. 9. 9. 16:04
DTO 생성
-Generate Getters and Setters... 사용해 메서드 생성import java.sql.Date; public class MemberDto { private int num; private String name; private String phone; private Date birth; private int bpoint; private Date joindate; private String gender; private int age; public int getNum() { return num; } public void setNum(int num) { this.num = num; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public Date getBirth() { return birth; } public void setBirth(Date birth) { this.birth = birth; } public int getBpoint() { return bpoint; } public void setBpoint(int bpoint) { this.bpoint = bpoint; } public Date getJoindate() { return joindate; } public void setJoindate(Date joindate) { this.joindate = joindate; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
DAO 생성
-import
import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList;
-class
public class MemberDao { private MemberDao() {} private static MemberDao itc=new MemberDao(); public static MemberDao getInstance() {return itc;} // 싱글톤 방식의 클래스를 만들어서 // 모든 객체가 현재 인스턴스를 공유해서 사용하도록 함 String driver="oracle.jdbc.OracleDriver"; String url="jdbc:oracle:thin:@localhost:1521:xe"; Connection con=null; PreparedStatement pstmt=null; ResultSet rs=null; private Connection getConnection() { Connection con=null; try { Class.forName(driver); con=DriverManager.getConnection(url, "scott", "tiger"); } catch (ClassNotFoundException e) {e.printStackTrace(); } catch (SQLException e) {e.printStackTrace(); } return con; } private void close() { try { if(con!=null) con.close(); if(pstmt!=null) pstmt.close(); if(rs!=null) rs.close(); } catch (SQLException e) {e.printStackTrace(); } } public ArrayList<MemberDto> selectAll(){ // memberlist 테이블에서 레코드를 꺼내서 // MemberDto에 하나씩 저장 // -> MemberDto를 다시 ArrayList에 저장 // -> 레코드 갯수만큼 저장된 MemberDto의 ArrayList를 리턴 // MemberDto들이 저장될 리스트 생성 ArrayList<MemberDto> list=new ArrayList<MemberDto>(); // sql문 작성 String sql="select*from memberlist order by num desc"; // 데이터베이스 연결 con=getConnection(); try { // sql과 con을 이용해서 pstmt(실행도구)를 설정 pstmt=con.prepareStatement(sql); // pstmt로 sql 실행 -> 실행결과 rs에 저장 rs=pstmt.executeQuery(); // rs.next(): 다음 데이터로 이동하는 메서드. // (다음데이터가 있으면 true 아니면 false 리턴) // rs.next()가 리턴해주는 true/false 값을 이용해서 // 데이터가 없을 때까지 반복실행 while(rs.next()) { // 각 레코드를 담을 MemberDto 생성. // 반복 실행마다 새롭게 만들어지는 객체 // 생성과 소멸을 반복하되, // 소멸되기 전에 저장된 객체 인스턴스들은 ArrayList에 저장됨 MemberDto mdto=new MemberDto(); // rs에서 필드값을 하나씩 꺼내서 // mdto의 해당멤버변수에 저장함 mdto.setNum(rs.getInt("num")); mdto.setName(rs.getString("name")); mdto.setPhone(rs.getString("phone")); mdto.setBirth(rs.getDate("birth")); mdto.setBpoint(rs.getInt("bpoint")); mdto.setJoindate(rs.getDate("joindate")); mdto.setGender(rs.getString("gender")); mdto.setAge(rs.getInt("age")); // 모든 필드값을 멤버변수에 저장한 객체인스턴스를 // ArrayList에 담음 list.add(mdto); } } catch (SQLException e) {e.printStackTrace(); } finally {close();}// 데이터베이스 연결종료 return list; } public int insertMember(MemberDto mdto) { // MemberDto 안에 저장된 멤버변수 값들을 // memberlist 테이블의 각 필드값으로 해서 레코드를 추가 int result=0; String sql="insert into memberlist(num,name,phone,birth," +"gender,age) values(member_seq.nextVal,?,?,?,?,?)"; con=getConnection(); try { pstmt=con.prepareStatement(sql); pstmt.setString(1, mdto.getName()); pstmt.setString(2, mdto.getPhone()); pstmt.setDate(3, mdto.getBirth()); pstmt.setString(4, mdto.getGender()); pstmt.setInt(5, mdto.getAge()); result=pstmt.executeUpdate(); } catch (SQLException e) {e.printStackTrace(); } finally {close();} return 0; } public MemberDto getMember(int num) { MemberDto mdto=null; String sql="select*from memberlist where num=?"; con=getConnection(); try { pstmt=con.prepareStatement(sql); pstmt.setInt(1, num); rs=pstmt.executeQuery(); if(rs.next()) { mdto=new MemberDto(); mdto.setNum(rs.getInt("num")); mdto.setName(rs.getString("name")); mdto.setPhone(rs.getString("phone")); mdto.setBirth(rs.getDate("birth")); mdto.setBpoint(rs.getInt("bpoint")); mdto.setJoindate(rs.getDate("joindate")); mdto.setGender(rs.getString("gender")); mdto.setAge(rs.getInt("age")); } } catch (SQLException e) {e.printStackTrace(); } finally {close();} return mdto; } public int updateMember(MemberDto mdto) { int result=0; // 전달된 mdto의 각 멤버변수값들로 해당하는 레코드를 수정함 String sql="update memberlist set name=?, phone=?, birth=?," + "gender=?, age=?, bpoint=?, joindate=? where num=?"; con=getConnection(); try { pstmt=con.prepareStatement(sql); pstmt.setString(1, mdto.getName()); pstmt.setString(2, mdto.getPhone()); pstmt.setDate(3, mdto.getBirth()); pstmt.setString(4, mdto.getGender()); pstmt.setInt(5, mdto.getAge()); pstmt.setInt(6, mdto.getBpoint()); pstmt.setDate(7, mdto.getJoindate()); pstmt.setInt(8, mdto.getNum()); result=pstmt.executeUpdate(); } catch (SQLException e) {e.printStackTrace(); } finally {close();} return result; } public int deleteMember(int num) { int result=0; String sql="delete from memberlist where num=?"; con=getConnection(); try { pstmt=con.prepareStatement(sql); pstmt.setInt(1, num); result=pstmt.executeUpdate(); } catch (SQLException e) {e.printStackTrace(); } finally {close();} return result; } }
Main 생성
-import
import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Scanner;
-static main
public static void main(String[] args) { Scanner sc=new Scanner(System.in); while(true) { System.out.println("\n---메뉴 선택---"); System.out.printf("1. 데이터열람 2. 데이터 추가 "); System.out.printf("3. 데이터 수정 4. 데이터 삭제 "); System.out.printf("5. 프로그램 종료. >> 메뉴선택: "); String choice=sc.nextLine(); if(choice.equals("5")) break; switch(choice) { case "1": select(); break; case "2": insert(); break; case "3": update(); break; case "4": delete(sc); break; default: System.out.println("메뉴 선택이 잘못되었음"); } } System.out.println("프로그램 종료"); }
-select
private static void select() { // MemberDao에 memberlist 테이블의 내용을 요청 // (selectAll 멤버메서드 호출)하고 리턴 받아서 화면에 테이블 내용을 출력. // database에 Access에서 테이블 내용을 읽어오고, // 레코드를 추가 수정하는 용도로 MemberDao를 생성함 // 그 안에 필요한 멤버메서드를 만들고 그들을 호출해서 // MemberMain에 필요한 작업들을 수행함 // 싱글턴 방식의 객체를 리턴 받아서 객체를 사용할 준비를 함 MemberDao mdao=MemberDao.getInstance(); // 멤버메서드 selectAll()를 호출하고, 그 메서드에서 리턴해주는 // ArrayList<MemberDto>형의 자료를 저장할 변수를 이어줌 ArrayList<MemberDto> list = mdao.selectAll(); // list 안에는 memberlist의 레코드들이 // MemberDto 객체 하나에 하나씩 저장되고 // ArrayList형으로 레코드 갯수만큼 담겨 있음 System.out.println("번호\t 이름\t\t 전화\t\t\t\t 생일 \t\t\t 포인트 \t나이\t성별 \t가입일"); System.out.println("--------------------------------------------------------------------------------------------"); for(MemberDto dto: list) { System.out.printf("%d \t %s \t %s \t %s \t %6d \t %3d \t %s \t %s\n", + dto.getNum(), dto.getName(), dto.getPhone(), + dto.getBirth(), dto.getBpoint(), dto.getAge(), + dto.getGender(), dto.getJoindate()); } }
-insert
private static void insert() { MemberDao mdao=MemberDao.getInstance(); MemberDto mdto=new MemberDto(); Scanner sc=new Scanner(System.in); // 필요한 입력값들을 입력받아서 // mdto에 해당 멤버변수에 저장하고, // mdao의 insertMember()메서드를 호출함 // 이때 mdto가 전달인수로 전달됨 System.out.printf("이름: "); mdto.setName(sc.nextLine()); System.out.printf("전화번호: "); mdto.setPhone(sc.nextLine()); System.out.printf("성별(F/M): "); mdto.setGender(sc.nextLine()); // 생일 입력 -java.util.Date() 형식의 입력 후 // java.sql.Date()로 변환이 필요함 // java.util.Date()의 입력을 위해선 // SimpleDateFromat의 parse 동작이 필요함 System.out.printf("생일(yyyy-MM-dd): "); SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd"); java.util.Date d=null; // 정확한 입력 형식대로 입력하지 않으면 다시 입력하는 반복실행문 while(true) { try { d=sdf.parse(sc.nextLine()); break; } catch(ParseException e) { System.out.print("날짜를 양식에 맞춰 다시 입력: "); } } // java.util.Date을 java.sql.Date로 변환 java.sql.Date birth=new java.sql.Date(d.getTime()); // mdto에 입력 mdto.setBirth(birth); // 나이 계산 Calendar c=Calendar.getInstance(); Calendar today=Calendar.getInstance(); c.setTime(d); // c.setTime(birth); Date 자료를 Calendar 자료로 변환 int age=today.get(Calendar.YEAR) -c.get(Calendar.YEAR) + 1; // 년도로 나이 계산 mdto.setAge(age); // mdto를 전달인수로 해서 insertMember 함수 호출, 결과 1, 리턴 0 int result=mdao.insertMember(mdto); if(result==1) System.out.println("레코드 추가 성공"); else System.out.println("레코드 추가 실패"); }
메뉴선택: 2 → insert 실행 -update
private static void update() { MemberDao mdao=MemberDao.getInstance(); MemberDto mdto=new MemberDto(); Scanner sc=new Scanner(System.in); int num; String input; while(true) { System.out.printf("수정할 회원번호: "); input=sc.nextLine(); if(input.equals(""))System.out.println("회원번호 입력 필수"); else break; } num=Integer.parseInt(input); // 입력된 회원번호로 회원 정보를 검색하고 리턴받음 mdto=mdao.getMember(num); if(mdto==null) { System.out.println("해당 회원 없음"); return; } // 이름 입력 후 빈칸이 아니라면 mdto에 저장 System.out.printf("이름 입력: %s",mdto.getName()); System.out.printf(" (수정하지 않으려면 엔터 입력) -> "); String name=sc.nextLine(); if(!name.equals("")) mdto.setName(name); // 전화번호 System.out.printf("전화 입력: %s -> ",mdto.getPhone()); String phone=sc.nextLine(); if(!phone.equals("")) mdto.setPhone(phone); // 성별 System.out.printf("성별 입력: %s -> ",mdto.getGender()); String gender=sc.nextLine(); if(!gender.equals("")) mdto.setGender(gender); // 포인트 System.out.printf("포인트 입력: %s -> ",mdto.getBpoint()); String bpoint=sc.nextLine(); if(!bpoint.equals(""))mdto.setBpoint(Integer.parseInt(bpoint)); // 생일과 나이 System.out.printf("생일 입력: %s -> ",mdto.getBirth()); SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd"); java.util.Date d=null; while(true) { try { String b=sc.nextLine(); // String으로 날짜 입력 if(b.equals("")) break; // 엔터만 입력했으면 반복 멈춤 d=sdf.parse(b); // java.util.Date로 변환 break; } catch(ParseException e) { System.out.print("날짜를 양식에 맞춰 다시 입력: "); e.printStackTrace(); } // 아무것도 입력안하거나 // 양식대로 입력해서 parse 함수가 에러가 안나면 while은 종료 } if(d!=null) { // 이 if문이 실행 안될 조건: d가 null // -> 아무것도 입력이 안돼서 d가 null인 경우 java.sql.Date birth=new java.sql.Date(d.getTime()); // java.sql.Date로 변환 mdto.setBirth(birth); // 수정을 위해 입력된 생년월일을 mdto에 저장 // 나이 계산 후 mdto에 저장 Calendar로 변환 후 년도끼리 뺄셈 Calendar c=Calendar.getInstance(); Calendar today=Calendar.getInstance(); c.setTime(d); int age=today.get(Calendar.YEAR) -c.get(Calendar.YEAR)+1; mdto.setAge(age); } // 회원가입일 수정-가입일자 후 빈칸이 아니라면 mdto에 저장 System.out.printf("가입일자:%S: ",mdto.getJoindate()); sdf=new SimpleDateFormat("yyyy-MM-dd"); d=null; while(true) { try { String b=sc.nextLine(); // String으로 날짜 입력 if(b.equals("")) break; // 엔터만 입력했으면 반복 멈춤 d=sdf.parse(b); // java.util.Date로 변환 break; } catch(ParseException e) { System.out.print("날짜를 양식에 맞춰 다시 입력: "); } } if(d!=null) { java.sql.Date joindate=new java.sql.Date(d.getTime()); mdto.setJoindate(joindate); } int result=mdao.updateMember(mdto); if(result==1) System.out.println("레코드 수정 성공"); else System.out.println("레코드 수정 실패"); }
메뉴선택: 3 → update 실행 -delete
private static void delete(Scanner sc) { MemberDao mdao=MemberDao.getInstance(); MemberDto mdto=null; int result, num; String input; // 삭제할 회원의 번호를 입력 받고 조회 후 // 회원이 있으면 삭제하고 없으면 "입력 회원 없음"과 함게 종료 while(true) { System.out.printf("삭제할 회원번호: "); input=sc.nextLine(); if(input.equals("")) System.out.println("회원번호 입력 필수"); else break; } num=Integer.parseInt(input); mdto=mdao.getMember(num); if(mdto==null) { System.out.println("해당 회원 없음"); return; } result=mdao.deleteMember(num); if(result==1) System.out.println("레코드 삭제 성공"); else System.out.println("레코드 삭제 실패"); }
메뉴선택: 4 → delete 실행 연습하기
Main
public static void main(String[] args) { Scanner sc=new Scanner(System.in); while(true) { System.out.println("\n---메뉴 선택---"); System.out.printf("1. 데이터 열람 2. 데이터 추가 "); System.out.printf("3. 데이터 수정 4. 데이터 삭제 "); System.out.printf("5. 프로그램 종료. >> 메뉴선택: "); String choice=sc.nextLine(); if(choice.equals("5")) break; switch(choice) { case "1": // select(); break; // select2(); break; select3(); break; case "2": insert(sc); break; case "3": update(sc); break; case "4": delete(sc); break; default: System.out.println("메뉴 선택이 잘못되었음"); } } System.out.println("프로그램 종료"); }
DAO_connection은 singleton으로 표현
private RentDao() {} private static RentDao itc=new RentDao(); public static RentDao getInstance() {return itc;} Connection con=null; PreparedStatement pstmt=null; ResultSet rs=null;
DTO: RentDto
public class RentDto { private String rentdate; private int num; private int bnum; private int mnum; private int discount; public String getRentdate() { return rentdate; } public void setRentdate(String rentdate) { this.rentdate = rentdate; } public int getNum() { return num; } public void setNum(int num) { this.num = num; } public int getBnum() { return bnum; } public void setBnum(int bnum) { this.bnum = bnum; } public int getMnum() { return mnum; } public void setMnum(int mnum) { this.mnum = mnum; } public int getDiscount() { return discount; } public void setDiscount(int discount) { this.discount = discount; } }
DTO: RentDetailDto
public class RentDetailDto { private String rentdate; private int num; private int mnum; private String mname; private int bnum; private String subject; private int rentprice; private int discount; private int rentprice2; public String getRentdate() { return rentdate; } public void setRentdate(String rentdate) { this.rentdate = rentdate; } public int getNum() { return num; } public void setNum(int num) { this.num = num; } public int getMnum() { return mnum; } public void setMnum(int mnum) { this.mnum = mnum; } public String getMname() { return mname; } public void setMname(String mname) { this.mname = mname; } public int getBnum() { return bnum; } public void setBnum(int bnum) { this.bnum = bnum; } public String getSubject() { return subject; } public void setSubject(String subject) { this.subject = subject; } public int getRentprice() { return rentprice; } public void setRentprice(int rentprice) { this.rentprice = rentprice; } public int getDiscount() { return discount; } public void setDiscount(int discount) { this.discount = discount; } public int getRentprice2() { return rentprice2; } public void setRentprice2(int rentprice2) { this.rentprice2 = rentprice2; } }
DataBaseManager Class 파일 생성
import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class DataBaseManager { private static String driver = "oracle.jdbc.driver.OracleDriver"; private static String url = "jdbc:oracle:thin:@localhost:1521:xe"; private static String id = "SCOTT"; private static String pw = "tiger"; public static Connection getConnection() { Connection con = null; try { Class.forName(driver); con = DriverManager.getConnection(url, id, pw); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } return con; } public static void close( Connection con, PreparedStatement pstmt, ResultSet rs ) { try { if(con!=null) con.close(); if(pstmt!=null) pstmt.close(); if(rs!=null) rs.close(); } catch (SQLException e) { e.printStackTrace(); } } }
case 1 - select
1) 첫번재 방법
// Main 코드 private static void select() { RentDao rdao=RentDao.getInstance(); ArrayList<RentDto> list = rdao.selectAll(); System.out.printf("날짜\t\t순번\t\t회원이름\t대여금액"); System.out.println("\t할인금액\t실제대여료\t도서제목"); System.out.println("-----------------------------" + "------------------------------------------"); for(RentDto rto: list) { System.out.printf("%s\t%d\t\t%d\t\t%d\t\t%d\n", rto.getRentdate(), rto.getNum(), rto.getMnum(), rto.getBnum(), rto.getDiscount()); } }
// DAO 코드 public ArrayList<RentDto> selectAll(){ ArrayList<RentDto> list= new ArrayList<RentDto>(); con=DataBaseManager.getConnection(); // 연결 String sql="select*from rentlist order by num desc"; try { pstmt=con.prepareStatement(sql); rs=pstmt.executeQuery(); while(rs.next()) { RentDto rdto=new RentDto(); rdto.setRentdate(rs.getString("rentdate")); rdto.setNum(rs.getInt("num")); rdto.setBnum(rs.getInt("bnum")); rdto.setMnum(rs.getInt("mnum")); rdto.setDiscount(rs.getInt("discount")); list.add(rdto); } } catch (SQLException e) {e.printStackTrace(); } finally {DataBaseManager.close(con,pstmt,rs);} return list; }
2) 두번째 방법
// Main 코드 private static void select2() { RentDao rdao=RentDao.getInstance(); ArrayList<RentDto> list = rdao.selectAll2(); System.out.printf("날짜\t\t순번\t\t회원이름\t대여금액"); System.out.println("\t할인금액\t실제대여료\t도서제목"); System.out.printf("----------------------------" + "-----------------------------------\n"); for(RentDto rto: list) { System.out.printf("%s\t%d\t\t%d\t\t%d\t\t%d\n", rto.getRentdate(), rto.getNum(), rto.getMnum(), rto.getBnum(), rto.getDiscount()); } }
// DAO 코드 public ArrayList<RentDto> selectAll2() { ArrayList<RentDto> list= new ArrayList<RentDto>(); con=DataBaseManager.getConnection(); // 연결 String sql="select to_char(rentdate,'YYYY-MM-DD HH24:MI') " + "as rd, num, bnum, mnum, discount " + "from rentlist order by num desc"; try { pstmt=con.prepareStatement(sql); rs=pstmt.executeQuery(); while(rs.next()) { RentDto rdto=new RentDto(); rdto.setRentdate(rs.getString("rd")); rdto.setNum(rs.getInt("num")); rdto.setBnum(rs.getInt("bnum")); rdto.setMnum(rs.getInt("mnum")); rdto.setDiscount(rs.getInt("discount")); list.add(rdto); } } catch (SQLException e) {e.printStackTrace(); } finally {DataBaseManager.close(con,pstmt,rs);} return list; }
3) 세번째 방법
// Main 코드 private static void select3() { RentDao rdao=RentDao.getInstance(); ArrayList<RentDetailDto> list = rdao.selectAll3(); System.out.printf("날짜\t\t순번\t\t회원이름\t대여금액"); System.out.println("\t할인금액\t실제대여료\t도서제목"); System.out.println("---------------------------------" + "---------------------------------------------------"); for(RentDetailDto rdto: list) { System.out.printf("%s\t%d\t\t%s\t\t%d\t\t%d\t\t%d\t\t%s\n", rdto.getRentdate(), rdto.getNum(), rdto.getMname(), rdto.getRentprice(), rdto.getDiscount(), rdto.getRentprice2(), rdto.getSubject()); } }
// SQL문 // SQL 파일 생성하여 실행 후 코드 진행 // rentdetail 테이블 생성됨 create or replace view rentdetail as select to_char(a.rentdate,'YY/MM/DD') as rd, a.num as rentnum, c.name as mname, b.subject, b.rentprice, a.discount, (b.rentprice-a.discount) as rentprice2 from rentlist a, booklist b, memberlist c where b.num=a.bnum and c.num=a.mnum order by rentnum desc;
// DAO 코드 public ArrayList<RentDetailDto> selectAll3() { ArrayList<RentDetailDto> list= new ArrayList<RentDetailDto>(); String sql="select*from rentdetail"; con=DataBaseManager.getConnection(); try { pstmt=con.prepareStatement(sql); rs=pstmt.executeQuery(); while(rs.next()) { RentDetailDto rdto = new RentDetailDto(); rdto.setRentdate( rs.getString("rd") ); rdto.setNum( rs.getInt("rentnum")); rdto.setMname( rs.getString("mname") ); rdto.setSubject( rs.getString("subject") ); rdto.setRentprice( rs.getInt("rentprice") ); rdto.setDiscount( rs.getInt("discount") ); rdto.setRentprice2( rs.getInt("rentprice2") ); list.add(rdto); } } catch (SQLException e) {e.printStackTrace(); } finally {DataBaseManager.close(con,pstmt,rs);} return list; }
실행 결과 case 2 - insert
// Main 코드 // 입력된 내용으로 레코드를 추가 // 도서번호를 입력할 때, // 해당 도서가 booklist에 있는지 검사하고 없으면 다시 입력하게 설정 // 회원번호가 입력할 때, // 해당 도서가 memberlist에 있는 검사하고 없으면 다시 입력하게 설정 // 둘 중 하나라도 입력없이 엔터만 치면 바로 종료되게 설정 private static void insert(Scanner sc) { RentDao rdao=RentDao.getInstance(); RentDto rdto=new RentDto(); // 대여할 도서번호 입력받음 int bnum=0; System.out.printf("대여할 도서번호: "); while(true) { String input=sc.nextLine(); if(input.equals("")) { System.out.printf("대여할 도서번호: "); continue; // 입력칸 빈칸이면 입력할 때까지 실행 } bnum=Integer.parseInt(input); boolean state=rdao.checkBookNum(bnum); if(state/*==true 생략 가능*/) break; else System.out.printf("도서가 존재하지 않음. 다시 입력: "); } rdto.setBnum(bnum); // 대여할 회원번호 입력받음 int mnum=0; System.out.printf("대여회원번호: "); while(true) { String input=sc.nextLine(); if(input.equals("")) { System.out.printf("대여회원번호: "); continue; } mnum=Integer.parseInt(input); boolean state=rdao.checkMemberNum(mnum); if(state/*==true 생략 가능*/) break; else System.out.printf("회원의 대여도서가 존재하지 않음. 다시 입력: "); } rdto.setMnum(mnum); // 할인금액 System.out.printf("할인금액: "); String input=sc.nextLine(); int discount=Integer.parseInt(input); rdto.setDiscount(discount); int result=rdao.inserRent(rdto); if(result==1) System.out.println("레코드 추가 성공"); else System.out.println("레코드 추가 실패"); }
// DAO 코드 public boolean checkBookNum(int bnum) { boolean result=false; String sql="select*from booklist where num=?"; con=DataBaseManager.getConnection(); try { pstmt=con.prepareStatement(sql); pstmt.setInt(1, bnum); rs=pstmt.executeQuery(); if(rs.next()) result=true; } catch (SQLException e) { } finally {DataBaseManager.close(con,pstmt,rs);} return result; } public boolean checkMemberNum(int mnum) { boolean result=false; String sql="select*from memberlist where num=?"; con=DataBaseManager.getConnection(); try { pstmt=con.prepareStatement(sql); pstmt.setInt(1, mnum); rs=pstmt.executeQuery(); if(rs.next()) result=true; } catch (SQLException e) { } finally {DataBaseManager.close(con,pstmt,rs);} return result; } public int inserRent(RentDto rdto) { int result=0; con=DataBaseManager.getConnection(); String sql="insert into rentlist(rentdate,bnum,mnum,discount)" + "values(rent_seq.nextVal,?,?,?)"; try { pstmt=con.prepareStatement(sql); pstmt.setInt(1, rdto.getBnum()); pstmt.setInt(2, rdto.getMnum()); pstmt.setInt(3, rdto.getDiscount()); result=pstmt.executeUpdate(); } catch (SQLException e) {e.printStackTrace(); } finally {DataBaseManager.close(con,pstmt,rs);} return result; }
insert 실행 결과 case 3 - update
// Main // 수정할 대여내역의 번호를 입력 받음. // (입력내용이 없거나 번호가 테이블에 존재하지 않으면 다시 입력) // 대여내역의 수정할 날짜 입력, 기존 도서제목을 보여주고 // 수정할 도서와 번호 입력, 기존 회원의 이름을 보여주고 // 수정할 회원번호 입력, 할인금액 입력 받아서 대여내역을 수정함. // 입력한 도서번호와 회원번호가 각 테이블에 없는 값일 때 다시 입력. private static void update(Scanner sc) { // 입력한 대여번호의 대여내역은 rentDetail 뷰에서 검색, // 최종 수정은 rentlist 테이블에서 수정 RentDao rdao=RentDao.getInstance(); // 입력받은 대여내역으로 뷰에서 num으로 검색 한번, // 테이블에서 num으로 검색 한번, 두번 검색이 이루어져야 // 위 내용의 실행이 원할함 // 대여번호 입력 System.out.printf("수정할 대여변호: "); int num=0; String input=""; RentDetailDto rddto=null; // 입력한 대여번호 조회한 기존 상세대여내역(RentDetail) // 이름과 제목 활용용도 RentDto rdto=null; // 입력한 대여번호로 조회한 기존 일반내역(Rentlist) // 수정할 데이터 저장용 while(true) { input=sc.nextLine(); if(input.equals("")) { System.out.printf("수정할 대여번호: "); continue; } num=Integer.parseInt(input); rddto=rdao.getRentDetail(num); rdto=rdao.getRent(num); if(rddto==null) System.out.println("입력한 number의 대여건이 없음. 재입력: "); else break; } // 수정할 대여날짜 입력 System.out.printf("대여일자: %s\t수정할 날짜 입력 ->", rddto.getRentdate()); String rentdate=sc.nextLine(); if(!rentdate.equals("")) rdto.setRentdate(rentdate); // 수정할 도서번호 입력 System.out.printf("도서제목: %s\t수정할 도서번호 입력 -> ", rddto.getSubject()); while(true) { input=sc.nextLine(); if(input.equals("")) break; num=Integer.parseInt(input); boolean state=rdao.checkBookNum(num); if(state) { rdto.setBnum(num); break; } } // 수정할 회원번호 입력 System.out.printf("회원이름: %s\t수정할 회원 이름 -> ", rdto.getDiscount()); while(true) { input=sc.nextLine(); if(input.equals("")) break; num=Integer.parseInt(input); boolean state=rdao.checkBookNum(num); if(state) { rdto.setMnum(num); break; } } // 할인금액 입력 System.out.printf("할인금액: "); String discount=sc.nextLine(); if(!discount.equals("")) rdto.setDiscount(Integer.parseInt(discount)); int result=rdao.updateRent(rdto); if(result==1) System.out.println("레코드 수정 성공"); else System.out.println("레코드 수정 실패"); }
// DAO public RentDetailDto getRentDetail(int num) { RentDetailDto rddto = null; String sql = "select * from rentdetail where rentnum = ?"; con = DataBaseManager.getConnection(); try { pstmt = con.prepareStatement(sql); pstmt.setInt(1, num); rs = pstmt.executeQuery(); if( rs.next() ) { rddto = new RentDetailDto(); rddto.setRentdate( rs.getString("rd") ); rddto.setNum( rs.getInt("rentnum") ); rddto.setSubject( rs.getString("subject") ); rddto.setMname( rs.getString("mname") ); rddto.setRentprice( rs.getInt("rentprice") ); rddto.setDiscount( rs.getInt("discount") ); rddto.setRentprice2( rs.getInt("rentprice2") ); } } catch (SQLException e) {e.printStackTrace(); } finally { DataBaseManager.close(con, pstmt, rs);} return rddto; } public RentDto getRent(int num) { RentDto rdto = null; String sql = "select to_char(rentdate, 'YYYY-MM-DD') as rd," + "num, bnum, mnum, discount " + "from rentlist where num = ?"; con = DataBaseManager.getConnection(); try { pstmt = con.prepareStatement(sql); pstmt.setInt(1, num); rs = pstmt.executeQuery(); if( rs.next() ) { rdto = new RentDto(); rdto.setRentdate( rs.getString("rd") ); rdto.setNum( rs.getInt("num") ); rdto.setBnum( rs.getInt("bnum") ); rdto.setMnum( rs.getInt("mnum") ); rdto.setDiscount( rs.getInt("discount")); } } catch (SQLException e) {e.printStackTrace(); } finally { DataBaseManager.close(con, pstmt, rs);} return rdto; } public int updateRent(RentDto rdto) { int result = 0; con = DataBaseManager.getConnection(); String sql = "update rentlist set rentdate = to_date(''||?||''" + ", 'YYYY-MM-DD') , " + " bnum =?, mnum=?, discount=? where num=?"; try { pstmt = con.prepareStatement(sql); pstmt.setString( 1, rdto.getRentdate() ); pstmt.setInt(2, rdto.getBnum() ); pstmt.setInt(3, rdto.getMnum() ); pstmt.setInt(4, rdto.getDiscount() ); pstmt.setInt( 5, rdto.getNum() ); result = pstmt.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } finally { DataBaseManager.close( con, pstmt, rs ); } return result; }
update 실행 결과 case 4- delete
// Main private static void delete(Scanner sc) { RentDao rdao=RentDao.getInstance(); RentDto rdto=null; // 수정할 대여번호 입력 System.out.printf("삭제할 대여건의 number을 입력: "); String input; while(true) { input=sc.nextLine(); if(input.equals("")) System.out.println("number 입력 필수"); else break; } int num=Integer.parseInt(input); rdto=rdao.getRent(num); if(rdto==null) { System.out.println("입력한 number의 대여건 없음"); return; } rdao.deleteRent(num); }
// DAO public int deleteRent(int num) { int result = 0; con = DataBaseManager.getConnection(); String sql = "delete from rentlist where num=?"; try { pstmt= con.prepareStatement(sql); pstmt.setInt(1, num); result = pstmt.executeUpdate(); } catch (SQLException e) {e.printStackTrace(); } finally { DataBaseManager.close( con, pstmt, rs ); } return result; }
delete 실행 결과 'DataBase > JDBC' 카테고리의 다른 글
[JDBC] DTO, DAO (0) 2022.09.09 [JDBC] 연습하기 (0) 2022.09.09 [JDBC] select, insert, update, delete (0) 2022.09.09 [JDBC] Java Database Connectivity (0) 2022.09.09