Connection 을 얻오오고 close 할 수 있는 메소드를 가진 DBUtil
package jdbcExam; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class DBUtil { // 접속하는 메소드 public static Connection getConnection() throws Exception{ String url = "jdbc:oracle:thin:@127.0.0.1:1521:xe"; String user = "smu"; String password = "smu"; return getConnection(url, user, password); }
public static Connection getConnection(String url,String user,String password) throws Exception{ Connection conn = null; // 3. 드라이버로딩 Class.forName("oracle.jdbc.driver.OracleDriver"); // 4.디비접속 conn = DriverManager.getConnection(url, user, password); return conn; } // close 하는 메소드 public static void close(Connection conn, PreparedStatement ps){ if (ps != null) { try { ps.close(); } catch (SQLException e) { e.printStackTrace(); } } if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } public static void close(Connection conn, PreparedStatement ps, ResultSet rs){ if (rs != null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } close(conn, ps); }
}
|
DBUtil을 이용한 BookDAO
package jdbcExam; import java.sql.Connection; import java.sql.PreparedStatement; public class BookDAO { public int addBook(String bookTitle, int page, String author, String content) { int insertCount = 0; Connection conn = null; PreparedStatement ps = null; try { conn = DBUtil.getConnection(); // 5. 쿼리작성 String sql = "insert into book values(book_seq.nextval,?,?,?,?,sysdate)"; ps = conn.prepareStatement(sql); ps.setString(1, bookTitle); ps.setInt(2, page); ps.setString(3, author); ps.setString(4, content); insertCount = ps.executeUpdate(); } catch (Exception e) { e.printStackTrace(); } finally { // 2. 닫는다. DBUtil.close(conn, ps); } return insertCount; } public void delBook(int bookId) { // 1. 선언 (필요한 객체 선언) Connection conn = null; PreparedStatement ps = null; try { conn = DBUtil.getConnection(); // 5. 쿼리작성 String sql = "delete book where book_id=?"; ps = conn.prepareStatement(sql); ps.setInt(1, bookId); // 6. 실행 ps.executeUpdate(); } catch (Exception e) { e.printStackTrace(); } finally { // 2. 닫는다. DBUtil.close(conn, ps); } } } |
'프로그래밍 > 자바' 카테고리의 다른 글
BookDAOTest (0) | 2016.01.14 |
---|---|
BookDAO , BookVO (0) | 2016.01.14 |
BookDAO (0) | 2016.01.14 |
수업중 기본명령 (0) | 2016.01.13 |
String&io 연습문제 (0) | 2016.01.12 |