본문 바로가기

Java 웹 개발

21.10.05 - 웹 개발 입문 37일차

36일차 과제 풀이

Q : 상품번호(no)를 입력받아 상품정보(product) 삭제

package jdbc.delete;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class Test01 {
	public static void main(String[] args) throws ClassNotFoundException, SQLException {
		//입력
		int no = 3;

		//처리
		Class.forName("oracle.jdbc.OracleDriver");
		Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "계정아이디", "계정비밀번호");

		String sql = "delete product where no = ?";
		PreparedStatement ps = con.prepareStatement(sql);

		ps.setInt(1, no);

		//ps.execute();//해당 명령으로는 삭제가 성공했는지 실패했는지 파악할 수 없다.
		int count = ps.executeUpdate();//해당 명령은 실행 후 적용된 행 개수를 반환한다.

		con.close();

		//결과 
		System.out.println("count = " + count);
		if(count > 0) {
			System.out.println("삭제 완료");
		}
		else {
			System.out.println("해당하는 상품이 존재하지 않습니다");
		}
	}
}

 

Q. 사용자에게 아이디(memberId)와 비밀번호(memberPw)를 입력받아 일치하는 회원 정보를 삭제

package jdbc.delete;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class Test02 {
	public static void main(String[] args) throws ClassNotFoundException, SQLException {
		//준비
		String memberId = "testuser1";
		String memberPw = "testuser1";

		//처리
		Class.forName("oracle.jdbc.OracleDriver");
		Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "계정아이디", "계정비밀번호");

		String sql = "delete member where member_id = ? and member_pw = ?";
		PreparedStatement ps = con.prepareStatement(sql);
		ps.setString(1, memberId);
		ps.setString(2, memberPw);

		int count = ps.executeUpdate();

		con.close();

		//결과
		System.out.println("count = " + count);
		if(count > 0) {
			System.out.println("회원 탈퇴가 완료되었습니다");
		}
		else {
			System.out.println("정보가 일치하지 않습니다");
		}
	}
}

 

 

 

-->  update 문제 풀이

 

Q. 상품번호와 상품가격을 입력받아 해당하는 번호의 상품 가격을 수정하세요
단, 존재하지 않는 상품 번호일 경우 사용자에게 없음을 알리는 메시지를 출력

package jdbc.update;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class Test01 {
	public static void main(String[] args) throws SQLException, ClassNotFoundException {
	
		//준비
		int no = 2;
		int price = 2500;

		//처리
		Class.forName("oracle.jdbc.OracleDriver");
		Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "계정아이디", "계정비밀번호");	

		String sql = "update product set price = ? where no = ?";
		PreparedStatement ps = con.prepareStatement(sql);
		ps.setInt(1, price);
		ps.setInt(2, no);
		int count = ps.executeUpdate();

		con.close();

		//출력
		if(count > 0) {
			System.out.println("가격 변경이 완료되었습니다");
		}
		else {
			System.out.println("존재하지 않는 상품 번호입니다");
		}

	}
}

 

 

Q. 상품번호와 상품이름, 상품분류, 상품가격, 제조일자, 유통기한을 모두 입력받아
해당하는 상품번호의 모든 정보를 수정하세요.
단, 조재하지 않는 상품 번호일 경우 사용자에게 없을을 알리는 메세지를 출력

package jdbc.update;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class Test02 {
	public static void main(String[] args) throws ClassNotFoundException, SQLException {
		//준비
		int no = 2;//고칠번호
		String name = "홈런볼";//바꿀이름
		String type = "과자";//바꿀분류
		int price = 3000;//바꿀가격
		String made = "2021-09-01";//바꿀 제조일자
		String expire = "2021-12-31";//바꿀 유통기한

		//처리
		Class.forName("oracle.jdbc.OracleDriver");
		Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "계정아이디", "계정비밀번호");

		String sql = "update product "
								+ "set name=?, type=?, price=?, "
								+ "made=to_date(?, 'YYYY-MM-DD'), "
								+ "expire=to_date(?, 'YYYY-MM-DD') "
							+ "where no = ?";
		PreparedStatement ps = con.prepareStatement(sql);
		ps.setString(1, name);
		ps.setString(2, type);
		ps.setInt(3, price);
		ps.setString(4, made);
		ps.setString(5, expire);
		ps.setInt(6, no);
		int count = ps.executeUpdate();

		con.close();

		//출력
		if(count > 0) {
			System.out.println("상품 정보 변경이 완료되었습니다");
		}
		else{
			System.out.println("상품 번호가 존재하지 않습니다");
		}

	}
}

 

Q. 아이디와 현재 비밀번호, 변경할 비밀번호를 입력받아 회원의 비밀번호를 변경하는 프로그램을 구현
성공했을 경우와 실패했을 경우 각각에 대한 메세지를 사용자에게 출력

package jdbc.update;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class Test03 {
	public static void main(String[] args) throws ClassNotFoundException, SQLException {
		// 준비
		String memberId = "testuser2";// 회원ID
		String memberPw = "testuser2";// 기존PW
		String newPw = "testuser1234";// 변경할PW

		// 처리
		Class.forName("oracle.jdbc.OracleDriver");
		Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "계정아이디", "계정비밀번호");

//		String sql = "update member "
//							+ "set member_pw = ? "
//							+ "where member_id = ? and member_pw = ?";
		String sql = "UPDATE MEMBER " + "SET MEMBER_PW = ? " + "WHERE MEMBER_ID = ? AND MEMBER_PW = ?";
		PreparedStatement ps = con.prepareStatement(sql);
		ps.setString(1, newPw);
		ps.setString(2, memberId);
		ps.setString(3, memberPw);
		int count = ps.executeUpdate();

		con.close();

		// 결과
		if (count > 0) {
			System.out.println("비밀번호 변경이 완료되었습니다");
		} else {
			System.out.println("비밀번호 변경에 필요한 정보가 잘못되었습니다");
		}
	}
}

 

 

Q. 사용자에게 아이디와 비밀번호, 수정할 정보들을 입력받아서 변경하는 프로그램을 구현
수정할 정보들은 아이디와 비밀번호를 제외하고 본인의 판단 하에 변경 가능한 정보들을 입력받아서 수정
성공했을 경우와 실패했을 경우 각각에 대한 메세지를 사용자에게 출력

package jdbc.update;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class Test04 {
	public static void main(String[] args) throws ClassNotFoundException, SQLException {
		// 준비
		String memberId = "testuser3";// 확인용ID
		String memberPw = "testuser3";// 확인용PW
		String memberNick = "임시3";// 변경할nickname
		String memberBirth = "2000-10-10";// 변경할 생년월일
		String memberEmail = "test3@kh.com";// 변경할 이메일
		String memberPhone = "010-1010-2020";// 변경할 전화번호

		// 처리
		Class.forName("oracle.jdbc.OracleDriver");
		Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "계정아이디", "계정비밀번호");

		String sql = "update member " + "set " + "member_nick=? , " + "member_birth = to_date(?, 'YYYY-MM-DD'), "
				+ "member_email = ?, " + "member_phone = ? " + "where " + "member_id = ? and member_pw = ?";
		PreparedStatement ps = con.prepareStatement(sql);
		ps.setString(1, memberNick);
		ps.setString(2, memberBirth);
		ps.setString(3, memberEmail);
		ps.setString(4, memberPhone);
		ps.setString(5, memberId);
		ps.setString(6, memberPw);
		int row = ps.executeUpdate();

		con.close();

		// 결과
		if (row > 0) {
			System.out.println("정보가 성공적으로 변경되었습니다");
		} else {
			System.out.println("정보 변경에 실패했습니다. 인증 정보가 일치하지 않습니다");
		}
	}
}

 

 

 

JDBC - 조회

사용할 수 있는 명령
1. rs.next() : 다음 줄로 포커스를 이동하는 명령(true/false 반환)
2. rs.get~~() : 포커스가 위치한 줄의 컬럼을 읽는 명령


while(다음줄에 데이터가 있다면) {
데이터를 꺼내세요(출력을 하든가 말든가)
}
while(true) {
if(다음줄에 데이터가 없다면) break;
else 데이터를 꺼내세요
}

package jdbc.select;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class Test01_2 {
	public static void main(String[] args) throws ClassNotFoundException, SQLException {
		//menu 테이블을 조회하는 프로그램

		//입력 없음

		//처리
		Class.forName("oracle.jdbc.OracleDriver");
		Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "계정아이디", "계정비밀번호");

		String sql = "select * from menu";
		PreparedStatement ps = con.prepareStatement(sql);
		//실행 시킨 뒤 발생하는 결과집합(ResultSet)을 반환하라!
		//= 결과집합은 데이터가 복사되어 저장된 형태가 아니라 영상통화처럼 참조만 가능한 형태이다
		//= 따라서 연결이 끊어지면 사용이 불가능하다
		ResultSet rs = ps.executeQuery();

		while(rs.next()) {
			System.out.print(rs.getString("menu_name"));
			System.out.print(" / ");
			System.out.print(rs.getInt("menu_price"));
			System.out.print(" / ");
			System.out.println(rs.getString("menu_type"));
		}

		con.close();

		//출력
		System.out.println("조회 완료");
	}
}

갈치조림 / 7000 / 식사
오므라이스 / 8500 / 식사
팥빙수 / 5000 / 디저트
오므라이스 / 8500 / 식사
조회 완료

 

 

Q. exam 테이블 조회 결과 출력

package jdbc.select;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class Test02 {
	public static void main(String[] args) throws SQLException, ClassNotFoundException {
		//exam 테이블 조회
		//= select * from exam;

		Class.forName("oracle.jdbc.OracleDriver");
		Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "계정아이디", "계정비밀번호");

		String sql = "select * from exam";
		PreparedStatement ps = con.prepareStatement(sql);
		ResultSet rs = ps.executeQuery();

		while(rs.next()) {
			System.out.print(rs.getInt(1));		//rs.getInt("exam_id")
            System.out.print(" / ");
			System.out.print(rs.getString(2));	//rs.getString("student")
            System.out.print(" / ");
			System.out.print(rs.getString(3));	//rs.getString("subject")
            System.out.print(" / ");
			System.out.print(rs.getString(4));	//rs.getString("type")
            System.out.print(" / ");
			System.out.println(rs.getInt(5));		//rs.getInt("score")
		}

		con.close();
	}
}

1 / 피카츄 / 프로그래밍언어활용 / 서술형 / 55
2 / 피카츄 / 프로그래밍언어활용 / 문제해결시나리오 / 95
3 / 피카츄 / 네트워크프로그래밍구현 / 서술형 / 60
4 / 피카츄 / 네트워크프로그래밍구현 / 평가자체크리스트 / 51
5 / 라이츄 / 프로그래밍언어활용 / 서술형 / 80
6 / 라이츄 / 프로그래밍언어활용 / 문제해결시나리오 / 52
7 / 라이츄 / 네트워크프로그래밍구현 / 서술형 / 58
8 / 라이츄 / 네트워크프로그래밍구현 / 평가자체크리스트 / 80
9 / 파이리 / 프로그래밍언어활용 / 서술형 / 54
10 / 파이리 / 프로그래밍언어활용 / 문제해결시나리오 / 81
11 / 파이리 / 네트워크프로그래밍구현 / 서술형 / 44
12 / 파이리 / 네트워크프로그래밍구현 / 평가자체크리스트 / 76
13 / 꼬부기 / 프로그래밍언어활용 / 서술형 / 100
14 / 꼬부기 / 프로그래밍언어활용 / 문제해결시나리오 / 60
15 / 꼬부기 / 네트워크프로그래밍구현 / 서술형 / 51
16 / 꼬부기 / 네트워크프로그래밍구현 / 평가자체크리스트 / 72
21 / 파이리 / 데이터입출력구현 / 포트폴리오 / 88
22 / 피카츄 / SQL활용 / 사례연구 / 75
41 / 어니부기 / 수학 / 수능 / 100

 

 

Q. product 테이블 조회 결과 출력

package jdbc.select;

import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class Test03 {
	public static void main(String[] args) throws SQLException, ClassNotFoundException {
		//product 조회
		//= select * from product;

		Class.forName("oracle.jdbc.OracleDriver");
		Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "계정아이디", "계정비밀번호");

		String sql = "select * from product";
		PreparedStatement ps = con.prepareStatement(sql);
		ResultSet rs = ps.executeQuery();

		while(rs.next()) {
			System.out.println("데이터 발견!");
			int no = rs.getInt("no");//rs.getInt(1)
			String name = rs.getString("name");//rs.getString(2)
			String type = rs.getString("type");//rs.getString(3)
			int price = rs.getInt("price");//rs.getInt(4)
			Date made = rs.getDate("made");//rs.getDate(5)
			Date expire = rs.getDate("expire");//rs.getDate(6)

			System.out.print("no = " + no);
			System.out.print(" / ");
			System.out.print("name = " + name);
			System.out.print(" / ");
			System.out.print("type = " + type);
			System.out.print(" / ");
			System.out.print("price = " + price);
			System.out.print(" / ");
			System.out.print("made = " + made);
			System.out.print(" / ");
			System.out.println("expire = " + expire);
		}

		con.close();
	}
}

데이터 발견!
no = 1 / name = 스크류바 / type = 아이스크림 / price = 1200 / made = 2020-05-01 / expire = 2020-10-01
데이터 발견!
no = 2 / name = 마이쮸 / type = 사탕 / price = 900 / made = 2020-01-01 / expire = 2021-01-01
데이터 발견!
no = 3 / name = 초코파이 / type = 과자 / price = 3000 / made = 2020-01-01 / expire = 2021-01-01
데이터 발견!
no = 4 / name = 맛동산 / type = 과자 / price = 2200 / made = 2020-02-01 / expire = 2020-10-20
데이터 발견!
no = 5 / name = 참이슬 / type = 주류 / price = 1000 / made = 2020-01-05 / expire = 2020-04-05
데이터 발견!
no = 6 / name = 처음처럼 / type = 주류 / price = 1000 / made = 2020-03-15 / expire = 2020-08-15
데이터 발견!
no = 7 / name = 바나나킥 / type = 과자 / price = 1500 / made = 2020-05-03 / expire = 2020-06-03
데이터 발견!
no = 8 / name = 빠삐코 / type = 아이스크림 / price = 1000 / made = 2019-12-01 / expire = 2020-06-01
데이터 발견!
no = 15 / name = 빅파이 / type = 과자 / price = 3000 / made = 2020-10-10 / expire = 2022-10-10
데이터 발견!
no = 9 / name = 멘토스 / type = 사탕 / price = 1200 / made = 2020-03-20 / expire = 2020-12-31
데이터 발견!
no = 10 / name = 오레오 / type = 과자 / price = 2100 / made = 2019-06-01 / expire = 2020-06-01

 

 

 

Q. member 테이블 조회 결과 출력

package jdbc.select;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class Test04 {
	public static void main(String[] args) throws ClassNotFoundException, SQLException {
		//member 조회하는 방법
		//1. 애초에 구문에서 중요정보를 제외하고 조회하는 방법 (안정성↑)
		//2. 전체 조회 후 원하는 정보만 출력 (확장성↑)

		Class.forName("oracle.jdbc.OracleDriver");
		Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "계정아이디", "계정비밀번호");

		String sql = "select * from member";
		PreparedStatement ps = con.prepareStatement(sql);
		ResultSet rs = ps.executeQuery();

		while(rs.next()) {
			System.out.println("데이터 발견");
			System.out.println("아이디 : "+rs.getString("member_id"));
			//System.out.println("비밀번호 : "+rs.getString("member_pw"));
			System.out.println("닉네임 : "+rs.getString("member_nick"));
			System.out.println("생년월일 : "+rs.getDate("member_birth"));
			System.out.println("이메일 : "+rs.getString("member_email"));
			System.out.println("전화번호 : "+rs.getString("member_phone"));
			System.out.println("가입일 : "+rs.getDate("member_join"));
			System.out.println("포인트 : "+rs.getInt("member_point"));
			System.out.println("등급 : "+rs.getString("member_grade"));
		}
		con.close();
	}
}

데이터 발견
아이디 : asdasd1234
닉네임 : 학생1237
생년월일 : 1990-05-25
이메일 : asd1234@aa.com
전화번호 : 010-1231-3453
가입일 : 2021-10-04
포인트 : 100
등급 : 준회원
데이터 발견
아이디 : qweqwe123
닉네임 : 안녕123
생년월일 : 1999-01-01
이메일 : qwe123@aa.com
전화번호 : 010-1234-1234
가입일 : 2021-10-04
포인트 : 100
등급 : 준회원

 

 

 

 

JDBC - 조건 필터링

조건을 통한 필터링
= 목록과 출력 방식이 동일하다.

package jdbc.select;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class Test05 {
	public static void main(String[] args) throws ClassNotFoundException, SQLException {
		//조건을 통한 필터링
		//= 목록과 출력 방식이 동일하다.

		//분류에 따른 메뉴 목록 출력

		//입력
		String menuType = "식사";

		//처리
		Class.forName("oracle.jdbc.OracleDriver");
		Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "계정아이디", "계정비밀번호");

		String sql = "select * from menu where menu_type = ?";
		PreparedStatement ps = con.prepareStatement(sql);
		ps.setString(1, menuType);
		ResultSet rs = ps.executeQuery();

		while(rs.next()) {
			System.out.print(rs.getString("menu_name"));
			System.out.print(" / ");
			System.out.print(rs.getInt("menu_price"));
			System.out.print(" / ");
			System.out.println(rs.getString("menu_type"));
		}

		con.close();
	}
}

갈치조림 / 7000 / 식사
오므라이스 / 8500 / 식사
오므라이스 / 8500 / 식사

 

 

Q. menu 테이블에서 사용자가 입력한 두개의 숫자 구간 사이의 가격대 메뉴를 조회하여 출력

package jdbc.select;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class Test06 {
	public static void main(String[] args) throws ClassNotFoundException, SQLException {
		//select * from menu where menu_price between 5000 and 8000;

		//입력
		int min = 5000;
		int max = 8000;

		//처리
		Class.forName("oracle.jdbc.OracleDriver");
		Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "계정아이디", "계정비밀번호");

		String sql = "select * from menu "
							+ "where menu_price between ? and ?";
		PreparedStatement ps = con.prepareStatement(sql);
		ps.setInt(1, min);
		ps.setInt(2, max);
		ResultSet rs = ps.executeQuery();

		while(rs.next()) {
			System.out.print(rs.getString("menu_name"));
			System.out.print(" / ");
			System.out.print(rs.getInt("menu_price"));
			System.out.print(" / ");
			System.out.println(rs.getString("menu_type"));
		}

		con.close();
	}
}

갈치조림 / 7000 / 식사
팥빙수 / 5000 / 디저트

 

 

 

Q. product 테이블에서 사용자가 입력한 검색어와 유사한 이름을 가지는 상품을 조회하여 출력

조건은 3가지가 있다

select * from product where name like '%바%';
select * from product where instr(name, '바') > 0;
select * from product where regexp_like(name, '바');

package jdbc.select;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class Test07 {
	public static void main(String[] args) throws ClassNotFoundException, SQLException {

		//입력
		String keyword = "바";

		//처리
		Class.forName("oracle.jdbc.OracleDriver");
		Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "계정아이디", "계정비밀번호");

		//String sql = "select * from product where regexp_like(name, ?)";
		//String sql = "select * from product where name like '%'||?||'%'";
		String sql = "select * from product where instr(name, ?) > 0";
		PreparedStatement ps = con.prepareStatement(sql);
		ps.setString(1, keyword);
		ResultSet rs = ps.executeQuery();

		while(rs.next()) {
			System.out.print(rs.getInt("no"));
			System.out.print(" / ");
			System.out.print(rs.getString("name"));
			System.out.print(" / ");
			System.out.print(rs.getString("type"));
			System.out.print(" / ");
			System.out.print(rs.getInt("price"));
			System.out.print(" / ");
			System.out.print(rs.getDate("made"));
			System.out.print(" / ");
			System.out.print(rs.getDate("expire"));
			System.out.println();
		}

		con.close();
	}
}

1 / 스크류바 / 아이스크림 / 1200 / 2020-05-01 / 2020-10-01
7 / 바나나킥 / 과자 / 1500 / 2020-05-03 / 2020-06-03