반응형
Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- discrete_scatter
- CES 2O21 참여
- CES 2O21 참가
- postorder
- classification
- Keras
- broscoding
- html
- paragraph
- web
- 결합전문기관
- KNeighborsClassifier
- pycharm
- 재귀함수
- 자료구조
- bccard
- vscode
- 데이터전문기관
- java역사
- inorder
- mglearn
- 웹 용어
- web 사진
- C언어
- web 용어
- web 개발
- 머신러닝
- tensorflow
- cudnn
- 대이터
Archives
- Today
- Total
bro's coding
jdbc.oracleDB.sequence를 활용한 방명록 관리 시스템 본문
반응형
package model;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
// DAO : Data Access Object
public class GuestBookDAO {
private String driver = "oracle.jdbc.OracleDriver";
private String url = "jdbc:oracle:thin:@127.0.0.1:1521:xe";
private String username = "scott";
private String pass = "tiger";
public GuestBookDAO() throws ClassNotFoundException {
Class.forName(driver);
}
public void closeAll(PreparedStatement pstmt, Connection con) throws SQLException {
if (pstmt != null)
pstmt.close();
if (con != null)
con.close();
}
public void closeAll(ResultSet rs, PreparedStatement pstmt, Connection con) throws SQLException {
if (rs != null)
rs.close();
closeAll(pstmt, con);
}
public void register(GuestBookDTO guestBookDTO) throws SQLException {
Connection con = null;
PreparedStatement pstmt = null;
try {
con = DriverManager.getConnection(url, username, pass);
StringBuilder sql = new StringBuilder("INSERT INTO guestbook(guestbook_no,title,content) ");
sql.append("VALUES(guestbook_seq.nextval,?,?)");
pstmt = con.prepareStatement(sql.toString());
pstmt.setString(1, guestBookDTO.getTitle());
pstmt.setString(2, guestBookDTO.getContent());
pstmt.executeUpdate();
} finally {
closeAll(pstmt, con);
}
}
public ArrayList<GuestBookDTO> getAllGuestBookOrderByNoDesc() throws SQLException {
ArrayList<GuestBookDTO> list = new ArrayList<GuestBookDTO>();
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
con = DriverManager.getConnection(url, username, pass);
String sql = "SELECT guestbook_no,title,content FROM guestbook ORDER BY guestbook_no DESC";
pstmt = con.prepareStatement(sql);
rs = pstmt.executeQuery();
while (rs.next()) {
list.add(new GuestBookDTO(rs.getInt(1), rs.getString(2), rs.getString(3)));
}
} finally {
closeAll(rs, pstmt, con);
}
return list;
}
// 방명록 글번호(guestbook_no) 의 현재값을 반환받기 위한 메서드
// sequence의 currval 는 단독으로 사용될 수 없으므로 아래 메세드는 Exception 발생된다
// 단독으로 사용 불가하는 것을 확인하는 메서드
public int getCurrentNo() throws SQLException {
int guestbookNo = 0;
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
con = DriverManager.getConnection(url, username, pass);
String sql = "select guestbook_seq.currval from dual";
pstmt = con.prepareStatement(sql);
rs = pstmt.executeQuery();
if (rs.next())
guestbookNo = rs.getInt(1);
} finally {
closeAll(rs, pstmt, con);
}
return guestbookNo;
}
/*
* 시퀀스를 이용해 방명록 글 번호를 발급받아 등록 -> insert sql 등록된 시퀀스(방명록 글 번호)의 현재값을 조회 -> select
* sql 위 두 sql을 하나의 컨넥션 ( 메서드 ) 에서 실행
*/
public void registerVer2(GuestBookDTO dto) throws SQLException {
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
con = DriverManager.getConnection(url, username, pass);
StringBuilder sql = new StringBuilder("INSERT INTO guestbook(guestbook_no,title,content) ");
sql.append("VALUES(guestbook_seq.nextval,?,?)");
pstmt = con.prepareStatement(sql.toString());
pstmt.setString(1, dto.getTitle());
pstmt.setString(2, dto.getContent());
pstmt.executeUpdate();
pstmt.close();
String sql2 = "SELECT guestbook_seq.currval FROM dual";
pstmt = con.prepareStatement(sql2);
rs = pstmt.executeQuery();
if (rs.next()) {
dto.setGuestbookNo(rs.getInt(1));
}
} finally {
closeAll(rs, pstmt, con);
}
}
}
package model;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
// DAO : Data Access Object
public class GuestBookDAO {
private String driver = "oracle.jdbc.OracleDriver";
private String url = "jdbc:oracle:thin:@127.0.0.1:1521:xe";
private String username = "scott";
private String pass = "tiger";
public GuestBookDAO() throws ClassNotFoundException {
Class.forName(driver);
}
public void closeAll(PreparedStatement pstmt, Connection con) throws SQLException {
if (pstmt != null)
pstmt.close();
if (con != null)
con.close();
}
public void closeAll(ResultSet rs, PreparedStatement pstmt, Connection con) throws SQLException {
if (rs != null)
rs.close();
closeAll(pstmt, con);
}
public void register(GuestBookDTO guestBookDTO) throws SQLException {
Connection con = null;
PreparedStatement pstmt = null;
try {
con = DriverManager.getConnection(url, username, pass);
StringBuilder sql = new StringBuilder("INSERT INTO guestbook(guestbook_no,title,content) ");
sql.append("VALUES(guestbook_seq.nextval,?,?)");
pstmt = con.prepareStatement(sql.toString());
pstmt.setString(1, guestBookDTO.getTitle());
pstmt.setString(2, guestBookDTO.getContent());
pstmt.executeUpdate();
} finally {
closeAll(pstmt, con);
}
}
public ArrayList<GuestBookDTO> getAllGuestBookOrderByNoDesc() throws SQLException {
ArrayList<GuestBookDTO> list = new ArrayList<GuestBookDTO>();
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
con = DriverManager.getConnection(url, username, pass);
String sql = "SELECT guestbook_no,title,content FROM guestbook ORDER BY guestbook_no DESC";
pstmt = con.prepareStatement(sql);
rs = pstmt.executeQuery();
while (rs.next()) {
list.add(new GuestBookDTO(rs.getInt(1), rs.getString(2), rs.getString(3)));
}
} finally {
closeAll(rs, pstmt, con);
}
return list;
}
// 방명록 글번호(guestbook_no) 의 현재값을 반환받기 위한 메서드
// sequence의 currval 는 단독으로 사용될 수 없으므로 아래 메세드는 Exception 발생된다
// 단독으로 사용 불가하는 것을 확인하는 메서드
public int getCurrentNo() throws SQLException {
int guestbookNo = 0;
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
con = DriverManager.getConnection(url, username, pass);
String sql = "select guestbook_seq.currval from dual";
pstmt = con.prepareStatement(sql);
rs = pstmt.executeQuery();
if (rs.next())
guestbookNo = rs.getInt(1);
} finally {
closeAll(rs, pstmt, con);
}
return guestbookNo;
}
/*
* 시퀀스를 이용해 방명록 글 번호를 발급받아 등록 -> insert sql 등록된 시퀀스(방명록 글 번호)의 현재값을 조회 -> select
* sql 위 두 sql을 하나의 컨넥션 ( 메서드 ) 에서 실행
*/
public void registerVer2(GuestBookDTO dto) throws SQLException {
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
con = DriverManager.getConnection(url, username, pass);
StringBuilder sql = new StringBuilder("INSERT INTO guestbook(guestbook_no,title,content) ");
sql.append("VALUES(guestbook_seq.nextval,?,?)");
pstmt = con.prepareStatement(sql.toString());
pstmt.setString(1, dto.getTitle());
pstmt.setString(2, dto.getContent());
pstmt.executeUpdate();
pstmt.close();
String sql2 = "SELECT guestbook_seq.currval FROM dual";
pstmt = con.prepareStatement(sql2);
rs = pstmt.executeQuery();
if (rs.next()) {
dto.setGuestbookNo(rs.getInt(1));
}
} finally {
closeAll(rs, pstmt, con);
}
}
}
package test;
import java.util.ArrayList;
import model.GuestBookDAO;
import model.GuestBookDTO;
public class TestGuestBookDAO {
public static void main(String[] args) {
try {
GuestBookDAO dao = new GuestBookDAO();
dao.register(new GuestBookDTO("사려니숲", "엠티가요~~"));
System.out.println("방명록 글등록 완료");
// 최근글부터 나오도록 글번호 내림차순으로 조회
ArrayList<GuestBookDTO> list = dao.getAllGuestBookOrderByNoDesc();
System.out.println("**방명록 리스트**");
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
package test;
import model.GuestBookDAO;
import model.GuestBookDTO;
public class TestGuestBookDAO2 {
public static void main(String[] args) {
try {
GuestBookDAO dao = new GuestBookDAO();
GuestBookDTO dto = new GuestBookDTO("강화도", "엠티가요~~");
dao.register(dto);
// 아래 실행결과는 title과 content 정보를 등록된 내용이지만 guestbookNo는 0이다
// 글 등록시 발급받은 글번호가 아니라 0이 출력된다
// 글 등록 후 발급받은 글번호를 확인하고자 할 경우에는 TestGuestBookDAO3 에서 확인하자
System.out.println("방명록 글등록 완료- 등록정보:" + dto);
} catch (Exception e) {
e.printStackTrace();
}
}
}
package test;
import model.GuestBookDAO;
import model.GuestBookDTO;
public class TestGuestBookDAO3 {
public static void main(String[] args) {
try {
GuestBookDAO dao = new GuestBookDAO();
// 시퀀스 현재값을 단독으로 받아오는 것을 불가능하다
// int currNo=dao.getCurrentNo();
// System.out.println("현재 시퀀스 정보:"+currNo);
GuestBookDTO dto = new GuestBookDTO("설악산", "엠티가요~~");
// 글 등록 시점에 guestbookNo 가 어떤 값으로 할당되었는 지 확인 가능한 메서드를 구현해서 확인
dao.registerVer2(dto);
System.out.println("방명록 글등록 완료- 등록정보:" + dto);
} catch (Exception e) {
e.printStackTrace();
}
}
}
반응형
'[IT] > jdbc' 카테고리의 다른 글
jdbc.basic architecture (0) | 2021.03.24 |
---|---|
jdbc.connection (0) | 2021.03.24 |
Comments