21.10.07 - 웹 개발 입문 39일차
JDBC - Update
[2] 수정(Update) 메소드
= update exam set student=?, subject=?, type=?, score=? where exam_id=?
= 준비물(매개변수) : ExamDto
= 결과물(반환형) : boolean
public boolean update(ExamDto examDto) throws Exception {
Connection con = JdbcUtils.connect(USERNAME, PASSWORD);
String sql = "update exam set student=?, subject=?, type=?, score=? where exam_id=?";
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, examDto.getStudent());
ps.setString(2, examDto.getSubject());
ps.setString(3, examDto.getType());
ps.setInt(4, examDto.getScore());
ps.setInt(5, examDto.getExamId());
int result = ps.executeUpdate();// 실행
con.close();
// result가 0보다 크다면 성공(true)했음을, 아니라면 실패(false)했음을 보고해라!
// if(result > 0) {
// return true;
// }
// else {
// return false;
// }
// result가 0보다 큰지 판단해서 보고해라!
return result > 0;
}
package jdbc.test;
import jdbc.beans.ExamDao;
import jdbc.beans.ExamDto;
public class Test04 {
public static void main(String[] args) throws Exception {
// 시험 정보 수정
// 입력 : ExamDto
ExamDto examDto = new ExamDto();
examDto.setExamId(5);
examDto.setStudent("또가스");
examDto.setSubject("데이터입출력구현");
examDto.setType("서술형");
examDto.setScore(99);
// 처리
ExamDao examDao = new ExamDao();
boolean isSuccess = examDao.update(examDto);
// 출력
if (isSuccess) {
System.out.println("변경이 완료되었습니다");
} else {
System.out.println("해당 번호의 정보가 없습니다");
}
}
}
변경이 완료되었습니다
[3] 이름만 수정하는 메소드
= update exam set student = ? where exam_id = ?
= 준비물 : ExamDto
= 결과물 : boolean
public boolean updateStudent(ExamDto examDto) throws Exception {
Connection con = JdbcUtils.connect(USERNAME, PASSWORD);
String sql = "update exam set student=? where exam_id=?";
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, examDto.getStudent());
ps.setInt(2, examDto.getExamId());
int result = ps.executeUpdate();
con.close();
return result > 0;
}
package jdbc.test;
import jdbc.beans.ExamDao;
import jdbc.beans.ExamDto;
public class Test04_1 {
public static void main(String[] args) throws Exception {
//질문 답변 : 시험 정보 수정(이름만)
//입력 : ExamDto
ExamDto examDto = new ExamDto();
examDto.setExamId(5);
examDto.setStudent("포포링");
//처리
ExamDao examDao = new ExamDao();
boolean isSuccess = examDao.updateStudent(examDto);
//출력
if(isSuccess) {
System.out.println("변경이 완료되었습니다");
}
else {
System.out.println("해당 번호의 정보가 없습니다");
}
}
}
변경이 완료되었습니다.
JDBC - Delete
[4] 데이터를 삭제하는 메소드
= PK를 이용하여 1개의 데이터를 삭제
= 매개변수 : Primary Key(시험지번호, exam_id) int
= 반환형 : boolean
public boolean delete(int examId) throws Exception {
Connection con = JdbcUtils.connect(USERNAME, PASSWORD);
String sql = "delete exam where exam_id = ?";
PreparedStatement ps = con.prepareStatement(sql);
ps.setInt(1, examId);
int result = ps.executeUpdate();
con.close();
return result > 0;
}
package jdbc.test;
import jdbc.beans.ExamDao;
public class Test09 {
public static void main(String[] args) throws Exception {
// exam 데이터 삭제 예제
//입력
int examId = 5;
//처리
ExamDao examDao = new ExamDao();
boolean success = examDao.delete(examId);
//출력
if(success) {
System.out.println("삭제 완료");
}
else {
System.out.println("존재하지 않는 시험지 번호");
}
}
}
삭제 완료
JDBC - Select
[5] 목록조회(R) 메소드(+검색)
= 여러 개의 데이터가 나오는 메소드
= select * from exam
= 매개변수 : 없음
= 반환형 : 시험지 목록(List<ExamDto>)
public List<ExamDto> select() throws Exception {
Connection con = JdbcUtils.connect(USERNAME, PASSWORD);
String sql = "select * from exam";
PreparedStatement ps = con.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
// rs에 들어있는 데이터를 새로 만든 List에 복사하여 반환
List<ExamDto> list = new ArrayList<>();// 1. 비어있는 List를 생성한다.
while (rs.next()) {// 2. 데이터 개수만큼 반복을 수행한다.
// 3. 한 줄씩 하나의 객체에 복사한다
ExamDto examDto = new ExamDto();
examDto.setExamId(rs.getInt("exam_id"));// rs의 exam_id를 객체에 복사
examDto.setStudent(rs.getString("student"));// rs의 student를 객체에 복사
examDto.setSubject(rs.getString("subject"));// rs의 subject를 객체에 복사
examDto.setType(rs.getString("type"));// rs의 type을 객체에 복사
examDto.setScore(rs.getInt("score"));// rs의 score를 객체에 복사
// 4. 만들어진 객체를 List에 추가한다.
list.add(examDto);
}
con.close();
return list;
}
package jdbc.test;
import java.util.List;
import jdbc.beans.ExamDao;
import jdbc.beans.ExamDto;
public class Test12 {
public static void main(String[] args) throws Exception {
// exam 목록 조회
// 입력 : 없음
// 처리
ExamDao examDao = new ExamDao();
List<ExamDto> list = examDao.select();
// 출력
System.out.println("개수 : " + list.size());
for (ExamDto examDto : list) {
System.out.print(examDto.getExamId());
System.out.print(" / ");
System.out.print(examDto.getStudent());
System.out.print(" / ");
System.out.print(examDto.getSubject());
System.out.print(" / ");
System.out.print(examDto.getType());
System.out.print(" / ");
System.out.print(examDto.getScore());
System.out.println();
}
}
}
개수 : 20
1 / 피카츄 / 프로그래밍언어활용 / 서술형 / 55
2 / 피카츄 / 프로그래밍언어활용 / 문제해결시나리오 / 95
3 / 피카츄 / 네트워크프로그래밍구현 / 서술형 / 60
4 / 피카츄 / 네트워크프로그래밍구현 / 평가자체크리스트 / 51
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
61 / 거북왕 / 데이터입출력구현 / 서술형 / 80
62 / 거북왕 / 데이터입출력구현 / 서술형 / 80
[6] 검색(R) 메소드
= 검색은 목록과 유사(데이터가 여러 개 나옴)
= 어떤 항목으로 검색할 것인지 정해야 한다.
= 학생 이름으로 검색한 결과를 출력하도록 구현(다른 형태도 가능)
= 매개변수 : 학생이름(String)
= 반환형 : 시험지정보목록(List<ExamDto>)
public List<ExamDto> selectByStudent(String student) throws Exception {
Connection con = JdbcUtils.connect(USERNAME, PASSWORD);
String sql = "select * from exam " + "where student = ? " + "order by exam_id asc";
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, student);
ResultSet rs = ps.executeQuery();
// rs에 들어있는 데이터를 새로 만든 List에 복사하여 반환
List<ExamDto> list = new ArrayList<>();// 1. 비어있는 List를 생성한다.
while (rs.next()) {// 2. 데이터 개수만큼 반복을 수행한다.
// 3. 한 줄씩 하나의 객체에 복사한다
ExamDto examDto = new ExamDto();
examDto.setExamId(rs.getInt("exam_id"));// rs의 exam_id를 객체에 복사
examDto.setStudent(rs.getString("student"));// rs의 student를 객체에 복사
examDto.setSubject(rs.getString("subject"));// rs의 subject를 객체에 복사
examDto.setType(rs.getString("type"));// rs의 type을 객체에 복사
examDto.setScore(rs.getInt("score"));// rs의 score를 객체에 복사
// 4. 만들어진 객체를 List에 추가한다.
list.add(examDto);
}
con.close();
return list;
}
package jdbc.test;
import java.util.List;
import jdbc.beans.ExamDao;
import jdbc.beans.ExamDto;
public class Test15 {
public static void main(String[] args) throws Exception {
//학생명으로 시험정보 검색
//입력 : 학생명(String)
String student = "피카츄";
//처리
ExamDao examDao = new ExamDao();
List<ExamDto> list = examDao.selectByStudent(student);
//출력 : 목록때와 동일
System.out.println("개수 : "+list.size());
for(ExamDto examDto : list) {
System.out.print(examDto.getExamId());
System.out.print(" / ");
System.out.print(examDto.getStudent());
System.out.print(" / ");
System.out.print(examDto.getSubject());
System.out.print(" / ");
System.out.print(examDto.getType());
System.out.print(" / ");
System.out.print(examDto.getScore());
System.out.println();
}
}
}
개수 : 5
1 / 피카츄 / 프로그래밍언어활용 / 서술형 / 55
2 / 피카츄 / 프로그래밍언어활용 / 문제해결시나리오 / 95
3 / 피카츄 / 네트워크프로그래밍구현 / 서술형 / 60
4 / 피카츄 / 네트워크프로그래밍구현 / 평가자체크리스트 / 51
22 / 피카츄 / SQL활용 / 사례연구 / 75
[7] 항목(column)과 검색어(keyword)를 이용한 검색 메소드
= (주의) 항목은 홀더처리하면 안된다
public List<ExamDto> select(String column, String keyword) throws Exception {
Connection con = JdbcUtils.connect(USERNAME, PASSWORD);
// String sql = "select * from exam where #1 = ? order by #1 asc";
String sql = "select * from exam where instr(#1, ?) > 0 order by #1 asc";
sql = sql.replace("#1", column);
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, keyword);
ResultSet rs = ps.executeQuery();
// rs에 들어있는 데이터를 새로 만든 List에 복사하여 반환
List<ExamDto> list = new ArrayList<>();// 1. 비어있는 List를 생성한다.
while (rs.next()) {// 2. 데이터 개수만큼 반복을 수행한다.
// 3. 한 줄씩 하나의 객체에 복사한다
ExamDto examDto = new ExamDto();
examDto.setExamId(rs.getInt("exam_id"));// rs의 exam_id를 객체에 복사
examDto.setStudent(rs.getString("student"));// rs의 student를 객체에 복사
examDto.setSubject(rs.getString("subject"));// rs의 subject를 객체에 복사
examDto.setType(rs.getString("type"));// rs의 type을 객체에 복사
examDto.setScore(rs.getInt("score"));// rs의 score를 객체에 복사
// 4. 만들어진 객체를 List에 추가한다.
list.add(examDto);
}
con.close();
return list;
}
package jdbc.test;
import java.util.List;
import jdbc.beans.ExamDao;
import jdbc.beans.ExamDto;
public class Test16 {
public static void main(String[] args) throws Exception {
// exam 테이블 항목, 검색어를 통한 검색
// 입력
String column = "student";
String keyword = "어니부기";
// 처리
ExamDao examDao = new ExamDao();
List<ExamDto> list = examDao.select(column, keyword);
// 출력
System.out.println("개수 : " + list.size());
for (ExamDto examDto : list) {
System.out.print(examDto.getExamId());
System.out.print(" / ");
System.out.print(examDto.getStudent());
System.out.print(" / ");
System.out.print(examDto.getSubject());
System.out.print(" / ");
System.out.print(examDto.getType());
System.out.print(" / ");
System.out.print(examDto.getScore());
System.out.println();
}
}
}
개수 : 1
41 / 어니부기 / 수학 / 수능 / 100
Q. 과제
1. 검색분류와 검색어를 입력받아 상품 검색 후 출력
public List<ProductDto> select(String column, String keyword) throws Exception {
Connection con = JdbcUtils.connect(USERNAME, PASSWORD);
String sql = "select * from product where instr(#1, ?) > 0 order by #1 asc";
sql = sql.replace("#1", column);
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, keyword);
ResultSet rs = ps.executeQuery();
List<ProductDto> list = new ArrayList<>();
while (rs.next()) {
ProductDto productDto = new ProductDto();
productDto.setNo(rs.getInt("no"));
productDto.setName(rs.getString("name"));
productDto.setType(rs.getString("type"));
productDto.setPrice(rs.getInt("price"));
productDto.setMade(rs.getString("made"));
productDto.setExpire(rs.getString("expire"));
list.add(productDto);
}
con.close();
return list;
}
package jdbc.test;
import java.util.List;
import jdbc.beans.ProductDao;
import jdbc.beans.ProductDto;
public class Test17 {
public static void main(String[] args) throws Exception {
String column = "price";
String keyword = "1500";
ProductDao productDao = new ProductDao();
List<ProductDto> list = productDao.select(column, keyword);
System.out.println("개수 : " + list.size());
for (ProductDto productDto : list) {
System.out.print(productDto.getNo());
System.out.print(" / ");
System.out.print(productDto.getName());
System.out.print(" / ");
System.out.print(productDto.getType());
System.out.print(" / ");
System.out.print(productDto.getPrice());
System.out.print(" / ");
System.out.print(productDto.getMadeDate());
System.out.print(" / ");
System.out.print(productDto.getExpireDate());
System.out.println();
}
}
}
개수 : 1
7 / 바나나킥 / 과자 / 1500 / 2020-05-03 / 2020-06-03
2. 검색분류와 검색어를 입력받아 회원 검색 후 출력
public List<MemberDto> select(String column, String keyword) throws Exception {
Connection con = JdbcUtils.connect(USERNAME, PASSWORD);
String sql = "select * from member where instr(#1, ?) > 0 order by #1 asc";
sql = sql.replace("#1", column);
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, keyword);
ResultSet rs = ps.executeQuery();
List<MemberDto> memberList = new ArrayList<>();
while (rs.next()) {
MemberDto memberDto = new MemberDto();
memberDto.setMemberId(rs.getString("member_id"));
memberDto.setMemberPw(rs.getString("member_pw"));
memberDto.setMemberNick(rs.getString("member_nick"));
memberDto.setMemberBirth(rs.getString("member_birth"));
memberDto.setMemberEmail(rs.getString("member_email"));
memberDto.setMemberPhone(rs.getString("member_phone"));
memberDto.setMemberJoin(rs.getString("member_join"));
memberDto.setMemberPoint(rs.getInt("member_point"));
memberDto.setMemberGrade(rs.getString("member_grade"));
memberList.add(memberDto);
}
con.close();
return memberList;
}
package jdbc.test;
import java.util.List;
import jdbc.beans.MemberDao;
import jdbc.beans.MemberDto;
public class Test18 {
public static void main(String[] args) throws Exception {
String column = "member_id";
String keyword = "asd";
MemberDao memberDao = new MemberDao();
List<MemberDto> memberList = memberDao.select(column, keyword);
System.out.println("개수 : " + memberList.size());
for (MemberDto memberDto : memberList) {
System.out.print(memberDto.getMemberId());
System.out.print(" / ");
System.out.print(memberDto.getMemberPw());
System.out.print(" / ");
System.out.print(memberDto.getMemberNick());
System.out.print(" / ");
System.out.print(memberDto.getMemberBirthDate());
System.out.print(" / ");
System.out.print(memberDto.getMemberEmail());
System.out.print(" / ");
System.out.print(memberDto.getMemberPhone());
System.out.print(" / ");
System.out.print(memberDto.getMemberJoin());
System.out.print(" / ");
System.out.print(memberDto.getMemberPoint());
System.out.print(" / ");
System.out.print(memberDto.getMemberGrade());
System.out.println();
}
}
}
개수 : 1
asdasd1234 / 12345675a / 학생1237 / 1990-05-25 / asd1234@aa.com / 010-1231-3453 / 2021-10-04 19:13:03 / 100 / 준회원