servlet/JDBC
JDBC - CRUD INSERT, UPDATE, DELETE
jddng
2022. 2. 4. 01:31
728x90
반응형
우선 쿼리문을 xml 파일에 작성
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
<entry key="insertMenu">
INSERT
INTO TBL_MENU A
(
A.MENU_CODE
, A.MENU_NAME
, A.MENU_PRICE
, A.CATEGORY_CODE
, A.ORDERABLE_STATUS
)
VALUES
(
SEQ_MENU_CODE.NEXTVAL
, ?
, ?
, ?
, ?
)
</entry>
<entry key="updateMenu">
UPDATE
TBL_MENU A
SET A.MENU_NAME = ?
, A.MENU_PRICE = ?
WHERE A.MENU_CODE = ?
</entry>
<entry key="deleteMenu">
DELETE
FROM TBL_MENU A
WHERE A.MENU_CODE = ?
</entry>
</properties>
참고
SELECT 수행 시에는 결과 값 ResultSet 인터페이스를 사용했지만
insert/update/delete에서는 ResultSet 은 필요가 없다
INSERT, UPDATE, DELETE
쿼리문만 달라지고 하는 방법은 같으므로 INSERT만 구현해보자
Properties prop = new Properties();
- xml 파일을 가져오기 위해 Properties 객체 생성
prop.loadFromXML(new FileInputStream("mapper/menu-query.xml"));
- xml파일 로드
String query = prop.getProperty("insertMenu");
- 수행할 쿼리를 xml파일의 key값을 이용하여 해당 쿼리를 가져온다
pstmt = con.prepareStatement(query);
- Connection인스턴스의 prepareStatement 메서드를 이용하여 PreparedStatement 객체 생성
pstmt.setString(1, "봉골레청국장");
pstmt.setInt(2, 50000);
pstmt.setInt(3, 4);
pstmt.setString(4, "Y");
- 해당 쿼리의 위치홀더에 데이터 바인딩
result = pstmt.executeUpdate();
- 해당 쿼리를 수행한 결과 값 반환(수행 시 결과 값 삽입/수정/삭제 된 행의 개수 (int) 반환)
- SELECT는 executeQuery() 메서드 사용,
INSERT/UPDATE/DELETE는 executeUpdate() 메서드를 사용한다.
전체 코드
public class Application1 {
public static void main(String[] args) {
Connection con = getConnection();
PreparedStatement pstmt = null;
/* SELECT 수행 시 결과 값 ResultSet 객체
* INSERT/UPDATE/DELTE 수행 시 결과 값 삽입/수정/삭제 된 행의 개수 (int)
* */
int result = 0;
Properties prop = new Properties();
try {
prop.loadFromXML(new FileInputStream("mapper/menu-query.xml"));
String query = prop.getProperty("insertMenu");
System.out.println(query);
pstmt = con.prepareStatement(query);
pstmt.setString(1, "봉골레청국장");
pstmt.setInt(2, 50000);
pstmt.setInt(3, 4);
pstmt.setString(4, "Y");
/* select시 executeQuery()
* insert/update/delete시 executeUpdate()
* */
result = pstmt.executeUpdate();
} catch (IOException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
close(pstmt);
close(con);
}
System.out.println("result : " + result);
}
}
728x90
반응형