refence lesson > 2022.02.03 - [JAVA] - [java] jdbc - SQL 테이블 생성 및 삭제, 시퀀스 부여
- 위 레슨의 테이블 생성을 참고하여, DB를 활성화 해주세요.
# jdbc Library
<CRUD 기능을 수행하는 예제>
- jdbc를 활용하여 DB와 상호작용하는 범위를 작성해보자.
1. 저장 데이터 속성 :
- num(데이터 번호), name(이름), age(나이), date(등록 일자)
2. 데이터 활용 기능 :
- insert(삽입), update(수정), delete(삭제), selectOne(1개 추출), selectAll(전체 나열), searchList(관련 정보 나열)
3. DB 정보
- URL = "jdbc:oracle:thin:@localhost:1521/xe";
- USER_ID ="JAVA";
- PASSWORD = "hi123456";
# 작성 순서
0. jdbc library 설치 / DB활성화(Table 생성)
1. class VO - 구현 데이터의 속성 정의 및 은닉화 >> hasCode, toString (2개 의미 찾기)
2. interface DAO - 구현 모델의 기능(CRUD) 정의 인터페이스(매소드 강제)
3-1. class DAOImpl - 오버라이딩 >> DB 연결 >> 매소드 기능 구현 >>
3-2. class Main - 매소드 동작 확인 >> 기능 확인
# Code - 최종 실행은 TestMain에서 실행합니다.
* 실습 코드의 모든 클래스/인터페이스 명은 03번으로 하였습니다. >> ex. Test03Main/ Test03DAO...
<TestVO>
package zava03Practice;
import java.io.Serializable;
import java.sql.Date;
import java.util.Objects;
public class Test03VO implements Serializable {
int num;
String name;
int age;
Date wdate;
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 int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Date getWdate() {
return wdate;
}
public void setWdate(Date wdate) {
this.wdate = wdate;
}
@Override
public String toString() {
return "Test03VO [num=" + num + ", name=" + name + ", age=" + age + ", wdate=" + wdate + "]";
}
@Override
public int hashCode() {
return Objects.hash(age, name, num, wdate);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Test03VO other = (Test03VO) obj;
return age == other.age && Objects.equals(name, other.name) && num == other.num
&& Objects.equals(wdate, other.wdate);
}
}
<TestDAO>
package zava03Practice;
import java.util.List;
public interface Test03DAO {
public int insert(Test03VO vo);
public int update(Test03VO vo);
public int delete(Test03VO vo);
public Test03VO selectOne(Test03VO vo);
public List<Test03VO> SelectAll();
public List<Test03VO> SearchList(String SearchKey, String SearchWord);
}
<TestDAOImpl>
package zava03Practice;
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.List;
public class Test03DAOImpl implements Test03DAO {
//oracle.jdbc library 설치
//DB 접속 정보
final String url = "jdbc:oracle:thin:@localhost:1521/xe";
final String userId = "JAVA";
final String password = "hi123456";
//DB 통신 준비
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
String sql = "";
public Test03DAOImpl() {
try {
Class.forName("oracle.jdbc.OracleDriver"); //Driver 등록
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}//constructor end
@Override
public int insert(Test03VO vo) {
System.out.println("insert()->"+vo); //입력 값 및 매소드 동작 확인
int flag = 0;
try {
conn = DriverManager.getConnection(url, userId, password); //DB connecting
System.out.println("conn successed..");
//SQL 송신
sql = "insert into test(num,name,age) values(SEQ_TEST.nextval,?,?)";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, vo.getName());
pstmt.setInt(2, vo.getAge());
flag = pstmt.executeUpdate(); //결과 값(삽입 데이터 갯수/int) 반환
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 선언 순서와 반대로 close() 진행 및 예외처리
if(rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}else if(pstmt != null) {
try {
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}else if(conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}//end finally
return flag;
}
@Override
public int update(Test03VO vo) {
System.out.println("update()->"+vo); //입력 값 및 매소드 동작 확인
int flag = 0;
try {
conn = DriverManager.getConnection(url, userId, password); //DB connecting
System.out.println("conn successed..");
//SQL 송신
sql = "update test set name=?, age=?, wdate=sysdate where num=?";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, vo.getName());
pstmt.setInt(2, vo.getAge());
pstmt.setInt(3, vo.getNum());
flag = pstmt.executeUpdate(); //결과 값(삽입 데이터 갯수/int) 반환
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 선언 순서와 반대로 close() 진행 및 예외처리
if(rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}else if(pstmt != null) {
try {
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}else if(conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}//end finally
return flag;
}
@Override
public int delete(Test03VO vo) {
System.out.println("delete()->"+vo); //입력 값 및 매소드 동작 확인
int flag = 0;
try {
conn = DriverManager.getConnection(url, userId, password); //DB connecting
System.out.println("conn successed..");
//SQL 송신
sql = "delete from test where num =?";
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, vo.getNum());
flag = pstmt.executeUpdate(); //결과 값(삽입 데이터 갯수/int) 반환
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 선언 순서와 반대로 close() 진행 및 예외처리
if(rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}else if(pstmt != null) {
try {
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}else if(conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}//end finally
return flag;
}
@Override
public Test03VO selectOne(Test03VO vo) {
System.out.println("selectOne()->"+vo); //입력 값 및 매소드 동작 확인
Test03VO vo2 = new Test03VO();
try {
conn = DriverManager.getConnection(url, userId, password); //DB connecting
System.out.println("conn successed..");
//SQL 송신
sql = "select * from test where num=?";
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, vo.getNum());
rs = pstmt.executeQuery(); //결과 값(삽입 배열 데이터/Test03VO) 반환
//'rs'에 저장된 값을 'vo2'인스턴스(객체)에 저장
while(rs.next()) {
vo2.setNum(rs.getInt("num"));
vo2.setName(rs.getString("name"));
vo2.setAge(rs.getInt("age"));
vo2.setWdate(rs.getDate("wdate"));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 선언 순서와 반대로 close() 진행 및 예외처리
if(rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}else if(pstmt != null) {
try {
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}else if(conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}//end finally
return vo2;
}
@Override
public List<Test03VO> SelectAll() {
System.out.println("SelectAll().."); //매소드 동작 확인
List<Test03VO> vos = new ArrayList<Test03VO>(); //가변 배열 활용
try {
conn = DriverManager.getConnection(url, userId, password); //DB connecting
System.out.println("conn successed..");
//SQL 송신
sql = "select * from test order by num desc";
pstmt = conn.prepareStatement(sql);
rs = pstmt.executeQuery(); //결과 값(삽입 배열 데이터/Test03VO) 반환
//'rs'에 저장된 값을 'vos'인스턴스(객체)에 저장
while(rs.next()) {
Test03VO vo = new Test03VO();
vo.setNum(rs.getInt("num"));
vo.setName(rs.getString("name"));
vo.setAge(rs.getInt("age"));
vo.setWdate(rs.getDate("wdate"));
vos.add(vo);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 선언 순서와 반대로 close() 진행 및 예외처리
if(rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}else if(pstmt != null) {
try {
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}else if(conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}//end finally
return vos;
}
@Override
public List<Test03VO> SearchList(String SearchKey, String SearchWord) {
System.out.println("SearchKey: "+SearchKey+" SearchWord: "+SearchWord); //입력 값 및 매소드 동작 확인
List<Test03VO> vos = new ArrayList<Test03VO>(); //가변 배열 활용
try {
conn = DriverManager.getConnection(url, userId, password); //DB connecting
System.out.println("conn successed..");
//키워드에 따라 처리 분기문 작성
//찾는 키워드 속성이 name인 경우
if(SearchKey == "name") {
//SQL 송신
sql = "select * from test where name = ?";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, SearchWord);
rs = pstmt.executeQuery(); //결과 값(삽입 배열 데이터/Test03VO) 반환
//'rs'에 저장된 값을 'vos'인스턴스(객체)에 저장
while(rs.next()) {
Test03VO vo = new Test03VO();
vo.setNum(rs.getInt("num"));
vo.setName(rs.getString("name"));
vo.setAge(rs.getInt("age"));
vo.setWdate(rs.getDate("wdate"));
vos.add(vo);
}
//찾는 키워드 속성이 age인 경우
}else if(SearchKey == "age") {
//SQL 송신
sql = "select * from test where age=?";;
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, SearchWord);
rs = pstmt.executeQuery(); //결과 값(삽입 배열 데이터/Test03VO) 반환
//'rs'에 저장된 값을 'vos'인스턴스(객체)에 저장
while(rs.next()) {
Test03VO vo = new Test03VO();
vo.setNum(rs.getInt("num"));
vo.setName(rs.getString("name"));
vo.setAge(rs.getInt("age"));
vo.setWdate(rs.getDate("wdate"));
vos.add(vo);
}
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 선언 순서와 반대로 close() 진행 및 예외처리
if(rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}else if(pstmt != null) {
try {
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}else if(conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}//end finally
return vos;
}
}
<TestMain>
package zava03Practice;
import java.util.List;
public class Test03Main {
public static void main(String[] args) {
System.out.println("Practice 03");
//데이터 처리 기능을 위한 객체 실체화(인스턴스화)
Test03DAOImpl dao = new Test03DAOImpl();
//insert 실행
Test03VO vo = new Test03VO();
vo.setName("lee11");
vo.setAge(55);
int result1 = dao.insert(vo);
System.out.println(result1);
//update 실행
vo = new Test03VO();
vo.setNum(3);
vo.setName("newkim");
vo.setAge(132);
int result2 = dao.update(vo);
System.out.println("result2: "+result2);
//delete 실행
vo = new Test03VO();
vo.setNum(3);
int result3 = dao.delete(vo);
System.out.println("result3: "+result3);
//selectOne 실행
vo = new Test03VO();
vo.setNum(5);
Test03VO result4 = dao.selectOne(vo);
System.out.println("result4: "+result4);
//selectAll 실행
List<Test03VO> result5 = dao.SelectAll();
System.out.println("result5: "+result5);
for (Test03VO x : result5) {
System.out.println(x);
}
//searchList - 'name' 실행
String key = "name";
String word = "park";
List<Test03VO> result6 = dao.SearchList(key,word);
for (Test03VO x : result6) {
System.out.println(x);
}
//searchList - 'age' 실행
key = "age";
word = "333";
List<Test03VO> result7 = dao.SearchList(key,word);
for (Test03VO x : result7) {
System.out.println(x);
}
}
}
# 결과값
<insert~selectAll>
<searchList>