YJ의 새벽

JDBC ( insert , update , select ) 본문

SelfStudy/JDBC

JDBC ( insert , update , select )

YJDawn 2023. 3. 17. 01:29

 

 

 

-- 기본생성자 클래스,                           ( VO 클래스 )     

-- DB 연결(Connection 생성)

   트랜잭션 제어

   JDBC 객체 자원 반환(close)   

   반복코드를 모아놓은 클래스            ( Template 클래스 )       

-- 실행부. main 메서드클래스             ( Run 클래스  )         1 순서

-- 데이터가공, 트랜잭션제어클래스    ( Service 클래스 )    2 순서

-- DB에서 SQL 수행,반환하는 클래스 ( DAO 클래스 )       3 순서

 

5 개의 클래스로 역할을 나누어 DB에 접근해본다. 

2 개의 .xml 파일로 DB접근 데이터를 나누어본다.

 

-- .xml 파일에  미리 쿼리문과,  DB 접근에 쓰일 driver 정보들을 따로 저장해놓는다 . 

-- xml 파일에 특화된 Properties 로  .xml에 접근한다.

 

 

  • Connect에 쓰일 driver 정보들을 .xml 에 저장해놓는다.
  • Properties를 통해 key 값으로 value를 받아온다.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
	<comment>driver.xml file</comment>
	
	<entry key="driver">oracle.jdbc.driver.OracleDriver</entry>
	<entry key="url">jdbc:oracle:thin:@localhost:1521:xe</entry>
	<entry key="user">kh</entry>
	<entry key="password">kh1234</entry>
</properties>

 

 

 

 

  • SQL 문을 .xml 파일에 저장해놓는다.
  • Properties를 통해 Key값으로 쿼리문을 받아온다.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
<comment>test-query.xml file</comment>

	<!-- TB_TEST 테이블 INSERT SQL -->
	<entry key="insert">
		INSERT INTO TB_TEST
		VALUES(?, ?, ?)
	</entry>
	
	<!-- TB_TEST 테이블 UPDATE SQL -->
	<entry key="update">
		UPDATE TB_TEST SET
		TEST_TITLE = ?,
		TEST_CONTENT = ?
		WHERE TEST_NO = ?
	</entry>
	<!-- TB_TEST 테이블 SELECT SQL -->
	<entry key="select">
		SELECT * FROM TB_TEST
	</entry>
</properties>

 

 

 

  •  반복코드를 모아놓은  Template 클래스 
  •  DB연결과 반환(close)하는 메서드를 모아놓았다.
public class JDBCTemplate {

	private static Connection conn = null;
	
	//Connection 
	public static Connection getConnection() {    
		try {
			if( conn==null || conn.isClosed()) {
				
				Properties prop = new Properties();
				prop.loadFromXML( new FileInputStream("driver.xml"));
				
				String driver = prop.getProperty("driver");
				String url = prop.getProperty("url");
				String user = prop.getProperty("user");
				String password = prop.getProperty("password");
				
				Class.forName(driver);
				conn = DriverManager.getConnection(url,user,password);
				
				conn.setAutoCommit(false);
			}
		}catch(Exception e) {
			System.out.println("[Connection중 예외발생]");
			e.printStackTrace();
		}
		return conn;
	}// end of getConnection()
	
	// Connection 반환
	public static void close(Connection conn) {
		try {
			if( conn!=null || !conn.isClosed()) {
				conn.close();
			}
		}catch(SQLException e) {
			e.printStackTrace();
		}
	}
	//Statement 반환
	public static void close(Statement stmt) {
		try {
			if( stmt!=null || !stmt.isClosed()) {
				stmt.close();
			}
		}catch(SQLException e) {
			e.printStackTrace();
		}
	}
	//ResultSet 반환
	public static void close(ResultSet rs) {
		try {
			if( rs!=null || !rs.isClosed()) {
				rs.close();
			}
		}catch(SQLException e) {
			e.printStackTrace();
		}
	}
	
	
	//Commit 
	public static void commit(Connection conn) {
		try {
			if( conn!=null || !conn.isClosed()) {
				conn.commit();
			}
		}catch(SQLException e) {
			e.printStackTrace();
		}
	}
	
	//Rollback
	public static void rollback(Connection conn) {
		try {
			if( conn!=null || !conn.isClosed()) {
				conn.rollback();
			}
		}catch(SQLException e) {
			e.printStackTrace();
		}
	}
}

 

 

 

 

  •   기본 생성자 VO 클래스 .
public class TestVO {

	private int testNo;
	private String testTitle;
	private String testContent;

	public TestVO() {}
	
	public TestVO(int testNo, String testTitle, String testContent) {
		this.testNo = testNo;
		this.testTitle = testTitle;
		this.testContent = testContent;
	}
	public int getTestNo() {
		return testNo;
	}
	public void setTestNo(int testNo) {
		this.testNo = testNo;
	}
	public String getTestTitle() {
		return testTitle;
	}
	public void setTestTitle(String testTitle) {
		this.testTitle = testTitle;
	}
	public String getTestContent() {
		return testContent;
	}
	public void setTestContent(String testContent) {
		this.testContent = testContent;
	}
}

 

 

 

 

 

  • insert 실행부. main 메서드클래스   ( Run 클래스  )         1 순서
  •  TestService클래스로 insert( '값' ) 를 넘겨준다.         --> 2 순서
public class Run {
	public static void main(String[] args) {
		
		TestService service = new TestService();
		
		TestVO vo = new TestVO(10,"추가할제목10","추가할내용10");
		
		try {
			int result = service.insert(vo);
			if(result > 0) {
				System.out.println("insert성공");
			}else {
				System.out.println("insert실패");
			}
		} catch (Exception e) {
			System.out.println("SQL수행중 오류발생");
			e.printStackTrace();
		}
	}
}

 

 

 

  • update 실행부. main 메서드클래스   ( Run 클래스  )         1 순서
  •  TestService클래스로 update( '값' ) 를 넘겨준다.         --> 2 순서
public class Run2 {
	public static void main(String[] args) {

		TestService service = new TestService();
		Scanner sc = new Scanner(System.in);
		
		System.out.print("번호를 입력하세요 : ");
		int no = sc.nextInt();
		sc.nextLine();
		System.out.print("바꿀 제목을 입력하세요 : ");
		String title = sc.nextLine();
		System.out.print("바꿀 내용을 입력하세요 : ");
		String content = sc.nextLine();
		
		TestVO vo = new TestVO(no,title,content);
		
		try {
			int result = service.update(vo);
			if( result > 0) {
				System.out.println("update 성공");
			}else {
				System.out.println("번호가 정확하지않습니다");
			}
		} catch (Exception e) {
			System.out.println("[update실행중 오류발생]");
			e.printStackTrace();
		}
	}
}

 

 

 

  • select 실행부. main 메서드클래스   ( Run 클래스  )         1 순서
  •  TestService클래스로 select () 를 넘겨준다.         --> 2 순서
public class Run3 {
	public static void main(String[] args) {

		TestService service = new TestService();
		
		try {
			service.select();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

 

 

 

 

 

 

 

 

  • 데이터가공, 트랜잭션제어클래스    ( Service 클래스 )                     2 순서
  • 1순서에서 받아온 insert( '값' ) , update( '값' ) , select() 메서드들에
  •        insert( conn, '값' ) , update( conn, '값' ) , select( conn )  conn 을 넣고 3순서로 .
  •        Connection을 매개변수로   DAO 클래스로 보낸다.
  • Connection 후  DB에서 실행할 DAO 클래스로 보낸다.                 --> 3순서
  • --  DAO에서 받아온 값에 대해 commit 과 rollback 적용.
public class TestService {

	private TestDAO dao = new TestDAO();
	
	// insert ////
	public int insert(TestVO vo) throws Exception {
		
		Connection conn = getConnection();
		
		int result = dao.insert(conn,vo);
		if( result >0 )                       // 3순서 ( DAO ) 에서 반환된값이 
			commit(conn);                     //  '1' (true) 라면 커밋. 아니면 롤백
		}else {
			rollback(conn);
		}
		return result;
	}
	
	// update ////
	public int update(TestVO vo) throws Exception {
		
		Connection conn = getConnection();
		int result = dao.update(conn,vo);
		
		if( result > 0 ) {                        // 3순서 ( DAO ) 에서 반환된값이 
			commit(conn);                     //  '1' (true) 라면 커밋. 아니면 롤백
		}else {
			rollback(conn);
		}
		return result;
	}
	
	// select ////
	public void select() throws Exception {
		
		Connection conn = getConnection();
		dao.select(conn);
		close(conn);
	}
}

 

 

 

 

 

 

  • -- DB에서 SQL 수행,반환하는 클래스 ( DAO 클래스 )       3 순서
public class TestDAO {
	
	private Statement stmt;
	private PreparedStatement pstmt;
	private ResultSet rs;
	private Properties prop;
	
	public TestDAO() {                    // 2순서 (Service) 에서
		prop = new Properties();          // 3순서 (DAO ) 를 호출하면
		try {                             //  만들어둔 쿼리문 (.xml) 을 바로 읽는다.
			prop.loadFromXML( new FileInputStream("test-query.xml"));
		} catch (Exception e) {
			e.printStackTrace();
		} 
	}
	
	
	// insert ////
	public int insert(Connection conn, TestVO vo) throws Exception {
		int result=0;
		
		try {
			String sql = prop.getProperty("insert");     // "insert" key값으로 insert문 호출
		
			pstmt = conn.prepareStatement(sql);
			pstmt.setInt(1, vo.getTestNo());
			pstmt.setString(2, vo.getTestTitle());
			pstmt.setString(3, vo.getTestContent());
			
			result = pstmt.executeUpdate();
		}finally {
			close(pstmt);
		}
		return result;                                  // 성공하면 1을 리턴해준다.
	}


	// update ////
	public int update(Connection conn, TestVO vo) throws Exception {
		
		int result = 0;
		
		try {
			String sql = prop.getProperty("update");     //"update" 키값으로 update 쿼리문 호출
			
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, vo.getTestTitle());
			pstmt.setString(2, vo.getTestContent());
			pstmt.setInt(3, vo.getTestNo());
			
			result=pstmt.executeUpdate();
			
		}finally {
			close(pstmt);
		}
		return result;                             // 성공하면 1을 리턴해준다.
	}


	// select ////
	public void select(Connection conn) throws Exception {

		try {
			String sql = prop.getProperty("select");     // "select" 키값으로 select 쿼리문호출
			
			stmt=conn.createStatement();
			rs = stmt.executeQuery(sql);              // select 문은 resultSet으로 결과반환.
			
			while( rs.next()) {
				int no = rs.getInt("TEST_NO");
				String title=rs.getString("TEST_TITLE");
				String content=rs.getString("TEST_CONTENT");
				System.out.println(no+" / "+title+" / "+content);
			}
		}finally {
			close(rs);
			close(stmt);
		}
	}
}

 

 

 

 

  •    insert  ,  update  는 
  • 성공하면  1 을 , 
  • 실패하면  0 을 반환해준다.
  •   1 순서  ->  2순서  ->  3순서      3순서에서 리턴받은 반환값으로
  •   1 순서  <-  2순서  <-  3순서      2순서에서 커밋과 롤백을 진행후
  •     run        service        DAO       1순서로 결과를 보낸다.

 

 

 

 

 

 

 

 

 

 

 

 

Comments