DAO(Data Access Object) : 데이터베이스의 데이터를 전문적으로 호출하고 제어하는 객체
SQL문 : car table, car_seq 시퀀스 생성
create table car(
num number primary key, --번호
name varchar2(30) not null, --이름
color varchar2(30) not null, --색상
maker varchar2(30) not null, --제조사
price number(9) not null, --가격
reg_date date not null --등록일
);
create sequence car_seq;
CarMain.java 클래스 생성
public class CarMain {
private BufferedReader br;
private CarDAO car;
public CarMain() {
try {
br = new BufferedReader(new InputStreamReader(System.in));
car = new CarDAO();
callMenu();
} catch (Exception e) {
e.printStackTrace();
} finally {
// 자원정리
if(br!=null)try {br.close();}catch(IOException e) {}
}
}
// 메뉴
private void callMenu() throws IOException{
while(true) {
System.out.print("1.등록,2.목록보기,3.상세정보,4.정보수정,5.정보삭제,6.종료>");
try {
int no = Integer.parseInt(br.readLine());
if(no == 1) {
// 정보등록
System.out.print("이름:");
String name = br.readLine();
System.out.print("색상:");
String color = br.readLine();
System.out.print("제조사:");
String maker = br.readLine();
// 가격은 0~99999999까지이므로 이걸 검사해주는 함수
int price = parseInputData("가격:");
car.insertCar(name, color, maker, price);
} else if(no == 2) {
// 목록보기
car.selectCar();
} else if(no == 3) {
// 상세정보
car.selectCar();
System.out.println("선택한 자동차 관리 번호:");
int num = Integer.parseInt(br.readLine());
System.out.println("------------");
int count = car.checkRecord(num);
if(count==1) {
car.selectDetailCar(num);
} else if(count==0) {
System.out.println("번호를 잘못입력했습니다.");
} else {
System.out.println("정보 처리 중 오류 발생");
}
} else if(no == 4) {
// 정보 수정
car.selectCar();
System.out.println("수정할 자동차 정보의 관리 번호:");
int num = Integer.parseInt(br.readLine());
int count = car.checkRecord(num);
if(count == 1) {
car.selectDetailCar(num);
System.out.println("-------------------");
System.out.print("이름:");
String name = br.readLine();
System.out.print("색상:");
String color = br.readLine();
System.out.print("제조사:");
String maker = br.readLine();
// 가격은 0~99999999까지이므로 이걸 검사해주는 함수
int price = parseInputData("가격:");
car.insertCar(name, color, maker, price);
} else if (count == 0) {
System.out.println("번호를 잘못 입력했습니다.");
} else {
System.out.println("정보 처리 중 오류 발생");
}
} else if(no == 5) {
// 정보 삭제
car.selectCar();
System.out.print("삭제할 정보의 관리 번호:");
int num = Integer.parseInt(br.readLine());
// 전달한 번호로 레코드 존재 여부 체크
int count = car.checkRecord(num);
// 1:존재, 0:미존재, -1:오류
if(count==1) car.deleteCar(num);
else if(count==0) System.out.println("번호를 잘못입력했습니다.");
else System.out.println("정보 처리 중 오류 발생");
} else if(no == 6){
System.out.println("프로그램 종료");
break;
} else {
System.out.println("잘못 입력했습니다.");
}
} catch (NumberFormatException e) {
System.out.println("[숫자를 입력 가능]");
} finally {
}
}
}
public int parseInputData(String item) throws IOException {
while (true) {
System.out.print(item);
try {
int num = Integer.parseInt(br.readLine());
// 0이하면 오류 발생
if(num<=0 || num > 999999999) {
throw new NotAcceptableValueException("1~999,999,999까지만 입력 가능");
}
return num; // 정상값 반환
} catch(NumberFormatException e) {
System.out.println("[숫자를 입력하지 않았거나 숫자 입력 범위를 초과했습니다.]");
} catch(NotAcceptableValueException e) {
System.out.println(e.getMessage());
}
}
}
public static void main(String[] args) {
new CarMain();
}
}
CarDAO.java 클래스 생성
public class CarDAO {
// 자동차 정보 등록
public void insertCar(String name,String color,String maker,int price) {
Connection conn = null;
PreparedStatement pstmt = null;
String sql = null;
int cnt = 0;
try {
// JDBC 수행 1,2단계
conn = DBUtil.getConnection();
// SQL문 작성
sql = "INSERT INTO car (num,name,color,maker,price,reg_date)
VALUES (car_seq.nextval,?,?,?,?,SYSDATE)";
// JDBC 수행 3단계
pstmt = conn.prepareStatement(sql);
// ?에 데이터 바인딩
pstmt.setString(++cnt, name);
pstmt.setString(++cnt, color);
pstmt.setString(++cnt, maker);
pstmt.setInt(++cnt, price);
// JDBC 수행 4단계
int count = pstmt.executeUpdate();
System.out.println(count + "개의 행을 삽입했습니다.");
} catch (Exception e) {
e.printStackTrace();
} finally {
// 자원정리
DBUtil.executeClose(null, pstmt, conn);
}
} // insertCar
// 목록보기
public void selectCar() {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
String sql = null;
try {
// JDBC 수행 1,2단계
conn = DBUtil.getConnection();
// SQL문 작성
sql = "SELECT * FROM car ORDER BY num DESC";
// JDBC 수행 3단계
pstmt = conn.prepareStatement(sql);
// JDBC 수행 4단계
rs = pstmt.executeQuery();
System.out.println("----------------------------------");
if(rs.next()) {
System.out.println("번호\t이름\t제조사\t등록일");
do {
System.out.print(rs.getInt("num"));
System.out.print("\t");
System.out.print(rs.getString("name"));
System.out.print("\t");
System.out.print(rs.getString("maker"));
System.out.print("\t");
System.out.println(rs.getDate("reg_date"));
} while(rs.next());
} else {
System.out.println("등록된 데이터가 없습니다.");
}
System.out.println("-------------------------------");
} catch (Exception e) {
e.printStackTrace();
} finally {
// 자원정리
DBUtil.executeClose(rs, pstmt, conn);
}
} // selectCar
// 조회하는 레코드가 존재하는지 여부 체크
public int checkRecord(int num) {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
String sql = null;
int count = 0;
try {
// JDBC 수행 1,2단계
conn = DBUtil.getConnection();
// SQL문 작성
sql = "SELECT * FROM car WHERE num=?";
// JDBC 수행 3단계
pstmt = conn.prepareStatement(sql);
// ?에 데이터 바인딩
pstmt.setInt(1, num);
// JDBC 수행 4단계
rs = pstmt.executeQuery();
if(rs.next()) {
count = 1; // 레코드가 존재할 때 1 저장
}
} catch (Exception e) {
count = -1; // 오류 발생
} finally {
// 자원정리
DBUtil.executeClose(rs, pstmt, conn);
}
return count;
} // checkRecord
// 자동차 상세보기
public void selectDetailCar(int num) {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
String sql = null;
try {
// JDBC 수행 1,2단계
conn = DBUtil.getConnection();
// SQL문 작성
sql = "SELECT * FROM car WHERE num=?";
// JDBC 수행 3단계
pstmt = conn.prepareStatement(sql);
// ?에 데이터 바인딩
pstmt.setInt(1, num);
// JDBC 수행 4단계
rs = pstmt.executeQuery();
if(rs.next()) {
System.out.println("번호 : " + rs.getInt("num"));
System.out.println("이름 : " + rs.getString("name"));
System.out.println("색상 : " + rs.getString("color"));
System.out.println("제조사 : " + rs.getString("maker"));
System.out.println("가격 : " + rs.getInt("price"));
System.out.println("등록일 : " + rs.getDate("reg_date"));
} else {
System.out.println("검색된 정보가 없습니다.");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 자원정리
DBUtil.executeClose(rs, pstmt, conn);
}
} // selectDetailCar
// 자동차 상세 정보 수정
public void updateCar(int num,String name,String color,String maker,int price) {
Connection conn = null;
PreparedStatement pstmt = null;
String sql = null;
int cnt = 0;
try {
// JDBC 수행 1,2단계
conn = DBUtil.getConnection();
// SQL문 작성
sql = "UPDATE car SET name=?,color=?,maker=?,price=? WHERE num=?";
// JDBC 수행 3단계
pstmt = conn.prepareStatement(sql);
// ?에 데이터 바인딩
pstmt.setString(++cnt, name);
pstmt.setString(++cnt, color);
pstmt.setString(++cnt, maker);
pstmt.setInt(++cnt, price);
pstmt.setInt(++cnt, num);
// JDBC 수행 4단계
int count = pstmt.executeUpdate();
System.out.println(count + "개 행의 정보를 수정했습니다.");
} catch (Exception e) {
e.printStackTrace();
} finally {
// 자원정리
DBUtil.executeClose(null, pstmt, conn);
}
} // updateCar
// 자동사 정보 삭제
public void deleteCar(int num) {
Connection conn = null;
PreparedStatement pstmt = null;
String sql = null;
try {
// JDBC 수행 1,2단계
conn = DBUtil.getConnection();
// SQL문 작성
sql = "DELETE FROM car WHERE num =?";
// JDBC 수행 3단계
pstmt = conn.prepareStatement(sql);
// ?에 데이터 바인딩
pstmt.setInt(1, num);
// JDBC 수행 4단계
int count = pstmt.executeUpdate();
System.out.println(count + "개 행을 삭제했습니다.");
} catch(Exception e) {
e.printStackTrace();
} finally {
DBUtil.executeClose(null, pstmt, conn);
}
} // deleteCar
}
NotAcceptableValueException.java 클래스 생성
public class NotAcceptableValueException extends Exception{
public NotAcceptableValueException(String str) {
super(str);
}
}
SQL문 작성 : member table 생성
create table member(
me_id varchar2(10) primary key,
me_passwd varchar2(10) not null,
me_name varchar2(30) not null,
me_phone varchar2(13) not null,
me_ragdate date default SYSDATE not null
);
MemberMain.java 클래스 생성
public class MemberMain {
private BufferedReader br;
private MemberDAO dao;
private String me_id; // 로그인한 아이디 저장
private boolean flag; // 로그인 여부
public MemberMain() {
try {
br = new BufferedReader(new InputStreamReader(System.in));
dao = new MemberDAO();
// 메뉴 호출
callMenu();
} catch (Exception e) {
e.printStackTrace();
} finally {
if(br!=null) try {br.close();} catch(IOException e) {}
}
}
// 메뉴 호출
private void callMenu() throws IOException {
// 로그인 체크 영역
while(true) {
System.out.println("1.로그인,2.회원가입,3.종료:");
try {
int no = Integer.parseInt(br.readLine());
if(no==1) {
// 로그인
System.out.print("아이디(입력취소:0):"); // 0은 아이디로 못쓰게 설정
me_id = br.readLine();
// 0이면 입력 취소
if(me_id.equals("0")) continue;
System.out.println("비밀번호:");
String me_passwd = br.readLine();
flag = dao.loginCheck(me_id, me_passwd);
if(flag) { // true
System.out.println(me_id+ "님 로그인 되었습니다.");
break;
}
System.out.println("아이디 또는 비밀번호가 불일치합니다."); // false
} else if(no==2) {
// 회원가입
} else if(no==3) {
// 종료
System.out.println("프로그램 종료");
break;
} else {
System.out.println("잘못 입력했습니다.");
}
} catch (NumberFormatException e) {
System.out.println("[숫자만 입력 가능]");
}
}
// 로그인 성공 후 회원제 서비스 영역
while(flag) {
System.out.print("1.상품목록,2.MY구매상품리스트,3.종료:");
try {
int no = Integer.parseInt(br.readLine());
if(no==1) {
// 상품목록
} else if(no==2) {
// MY구매상품리스트
} else if(no==3) {
// 종료
System.out.println("프로그램 종료");
break;
} else {
System.out.println("잘못 입력했습니다.");
}
} catch(NumberFormatException e){
System.out.println("[숫자만 입력 가능]");
}
}
}
public static void main(String[] args) {
new MemberMain();
}
}
MemberDAO 클래스 생성
public class MemberDAO {
// 사용자 로그인 체크(로그인 성공 true, 로그인 실패 false 반환)
public boolean loginCheck(String me_id,String me_passwd) {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
String sql = null;
boolean flag = false;
try {
// JDBC 수행 1,2단계
conn = DBUtil.getConnection();
// SQL문 작성
sql = "SELECT me_id FROM member WHERE me_id=? AND me_passwd=?";
// JDBC 수행 3단계
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, me_id);
pstmt.setString(2, me_passwd);
// JDBC 수행 4단계
rs = pstmt.executeQuery();
if(rs.next()) {
flag = true; // 로그인 성공, 기본이 false라 else문 필요X
}
}catch (Exception e) {
e.printStackTrace();
// flag = false; 로 예외발생 시 다른 것 추가할 수 있음
}finally {
// 자원정리
DBUtil.executeClose(rs, pstmt, conn);
}
return flag;
}
}