728x90
Statement로 sql을 적용시키고, 같은 명령을 값만 바꿔서 더 빠르게 처리하기 위해서 PreparedStatement를 사용해서 아래 코드로 insert와 select를 만들었다.
그런데도 그 코드는 다른 기능과 함께 사용하려면 아마 함수나 객체로 만들어 처리하는게 더 가시적이고 편할 것이다.
즉 데이터베이스의 CRUD를 모듈화 한 것이 DAO이다.
try{
Class.forName("com.mysql.jdbc.Driver");
String url ="jdbc:mysql://localhost:3306/hellojdbc?serverTimezone=UTC";
conn = DriverManager.getConnection(url, "root", "root");
System.out.println("연결 성공");
Statement stat=conn.createStatement();
String sql = "insert into logininfo (id, pw) values (?,?)";
PreparedStatement pstat = conn.prepareStatement(sql);
pstat.setString(1,"id123");
pstat.setString(2,"pw123");
pstat.executeUpdate();
sql = "select * FROM logininfo WHERE id= (?)";
pstat = conn.prepareStatement(sql);
pstat.setString(1, "admin");
rs =pstat.executeQuery();
while(rs.next()) {
String id =rs.getString("id");
String pw =rs.getString("pw");
System.out.println(id+" "+pw);
}
rs.close();
}
catch(ClassNotFoundException e){
System.out.println(e+"드라이버 로딩 실패");
}
catch(SQLException e){
System.out.println("에러: " + e);
}
finally{
try{
if( conn != null && !conn.isClosed()){
conn.close();
}
}
catch( SQLException e){
e.printStackTrace();
}
}
DAO / Data Access Object
db 연결과 쿼리 적용을 위한 객체를 만들었다.
생성 시, db와 연결하고, 기능에 따라 sql을 적용한다.
이런 모듈화로 servlet에서 사용하기도 편하고, 데이터베이스를 다루는 코드 자체도 관리가 편해질 것이다.
public class AccountDAO {
Connection conn = null;
public AccountDAO(){
Class.forName("com.mysql.cj.jdbc.Driver");
String url ="jdbc:mysql://localhost:3306/hellojdbc?serverTimezone=UTC";
conn = DriverManager.getConnection(url, "root", "root");
}
public int insertAccount(String newId, String newPw) {
String sql = "insert into logininfo (id, pw) values (?,?)";
PreparedStatement pstat = null;
int result = 0;
pstat = conn.prepareStatement(sql);
pstat.setString(1,newId);
pstat.setString(2,newPw);
result = pstat.executeUpdate();
if( conn != null) conn.close();
if( pstat != null) pstat.close();
return result;
}
}
다만 insert를 위해선 해당 새로운 데이터의 컬럼(newId, newPw)를 파라미터로 입력해줘야한다.
또 select를 구현하다고 치면, 해당 데이터의 컬럼 목록을 다 포함할 수 있는 배열의 list를 반환하도록 해야할 것이다.
그냥 데이터베이스의 컬럼을 변수로 갖는 클래스를 만들어 관리하면 어떨까. 객체 자체가 마치 하나의 데이터처럼 사용되는 것이다.
DTO / Data Transfer Obejct
데이터베이스의 자료를 자바에서 쓸 수 있도록 전환해주는 클래스를 정의한다.
데이터베이스를 구성하는 칼럼을 변수로 갖고, getter와 setter로 자료를 저장하고 가져온다.
public class AccountDTO {
int no;
String id = null;
String pw = null;
public AccountDTO(int no, String id, String pw) {
this.no = no;
this.id = id;
this.pw = pw;
}
public int getNo() {
return no;
}
public String getId() {
return id;
}
public String getPw() {
return pw;
}
}
참조
728x90
'백엔드 > JSP & Servlet' 카테고리의 다른 글
JDBC API를 이용해서 두 개 이상의 쿼리를 트랜잭션으로 묶어서 처리 (0) | 2021.07.23 |
---|---|
웹 어플리케이션 구동 시 JDBC 드라이버 로딩하기 (0) | 2021.07.23 |
JSP LONG VARCHAR 타입 값 일어오기 (mysql) (0) | 2021.07.23 |
JSP JDBC 이용해 mysql 연결 (0) | 2021.07.23 |
이클립스에서 JSP로 개발 시 파일 경로 설정 이해 (0) | 2021.07.17 |