Notice
Recent Posts
Recent Comments
Link
«   2024/09   »
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
29 30
Tags
more
Archives
Today
Total
관리 메뉴

개발 일기

DAO 클래스를 더욱 간단하게! DataSource 클래스를 따로 만들어보기 본문

JAVA 연습장

DAO 클래스를 더욱 간단하게! DataSource 클래스를 따로 만들어보기

개발 일기 2021. 7. 26. 22:18

안녕하세요.

 

JDBC의 DAO 클래스를 VO 클래스를 활용하여 만드는 작업까지 진행을 해보았는데요.

DAO 클래스의 CRUD 메소드(insert, delete 등등)에 DB접근 단계를 위한 클래스를 따로 만들어 활용해보겠씁니다.

 

1. DataSource 클래스 만들기

 - Driver 클래스 객체 생성

 - Connection 객체 생성(DBServer에 연결)

public class DataSource {
	
	public Connection getConnection() throws Exception{
		String driverClass= "oracle.jdbc.OracleDriver";
		String url = "jdbc:oracle:thin:@182.237.126.19:1521:xe";
		String user = "DB접속정보";
		String password = "DB접속정보";
		
		Class.forName(driverClass);
		Connection con = DriverManager.getConnection(url,user,password);
		return con;
		
	}
	
	public void releaseConnection(Connection con) throws Exception{
		con.close();
		
	}

}

 => DB Connection 단계를 클래스화 함

 

2. DAO 클래스에 DataSource 클래스 활용

public class AddressDao {
	private DataSource dataSource;

	public AddressDao() {
		this.dataSource = new DataSource();
	}

	public Address selectByNo(int no) throws Exception {

		Address findAddress = null;
		String selectSql = "select no,id,name,phone,address from address where no = ?";

		Connection con = dataSource.getConnection();
		PreparedStatement pstmt = con.prepareStatement(selectSql);
		pstmt.setInt(1, no);

		ResultSet rs = pstmt.executeQuery();

		while (rs.next()) {

			int n = rs.getInt("no");
			String id = rs.getString("id");
			String name = rs.getString("name");
			String phone = rs.getString("phone");
			String address = rs.getString("address");
			findAddress = new Address(n, id, name, phone, address);
		}

		rs.close();
		pstmt.close();

		dataSource.releaseConnection(con);
		return findAddress;
	}
}

 => DataSource 테이블의 dataSource 객체 생성 후 insert 메소드 내 DB접근정보 기재하지 않고

      getConnection 메소드 호출하여 DB접근정보 받아서 사용함

 

 

DB에 접근하기 위한 소스를 클래스 객체화하여 DAO클래스를 보다 간단하게 수정해보았습니다.

감사합니다!

Comments