Back_end/JSP

JSP - CRUD

hyeon1016 2024. 11. 4. 02:00

CRUD 

CREATE, READ, UPDATE, DELETE라는 DB의 기본적인 데이터 조작을 뜻한다.

 

시작하기 앞서...

1. 많이 사용하는 DB연결 메서드는 함수 처리 하여 코드를 최대한 줄이겠다. 

2. TEST DB에는 test01이라는 테이블이 있으며, id, password, name 컬럼이 포함되어 있다.

3. member_dto 클래스도 미리 만들어 두겠다.

 

 

DTO

public class member_dto {
	private String id;
	private String password;
	private int name;
	
	...getter setter
}

 

DBconn()

private Connection DBconn() throws Exception{
	// Step 1. JDBC 드라이버 로딩
	Class.forName("com.mysql.jdbc.Driver");
	// Step 2. Connection 객체 생성 : 확인 사항 1. 데이터베이스 생성 여부 2. WEB-INF 폴더에 라이브러리 확인
	Connection conn = null;
	String database = "jdbc:mysql://localhost:3306/TEST";
	String id = "root";
	String password = "1234";
	conn = DriverManager.getConnection(database, id, password);
	System.out.println("데이터 베이스 연결 완료");
	return conn;
}

 

 

CREATE

*DB에 추가할 정보를 가진 member_dto가 필요하다.

public void create(member_dto mb){
	//DB 연결
	Connection conn = DBconn();
	//SQL 전송
	System.out.println("SQL전송 시도");
	PreparedStatement pstmt = null;
	String sql = "insert into member values(?,?,?)";
	try {
		pstmt = conn.prepareStatement(sql);
		pstmt.setString(1, mb.getId());
		pstmt.setString(2, mb.getPassword());
		pstmt.setString(3, mb.getName());
			
		System.out.println("전송되는 SQL : "+pstmt);
			
		pstmt.executeUpdate();
		System.out.println("SQL전송 성공");
        
	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} finally {
		...생략
	}
}

 

READ

특정 DTO만 읽기(DTO / if)

*특정 DTO를 읽어오기 위한 DTO의 id, password, name중 하나의 값이 필요하다.

public member_dto getOneMember(String id) {
	member_dto mb = new member_dto();
	PreparedStatement pstmt = null;
	ResultSet rs = null;
	String sql = null;
	//데이터베이스 연결
	Connection conn = dbconn();
	try {
		//SQL전송
		sql = "select * from test01 where id=?";
		pstmt = conn.prepareStatement(sql);
		pstmt.setString(1, id);
		rs = pstmt.executeQuery();
		//ResultSet을 객체로 전환
		if(rs.next()) {
			String memberId = rs.getString("id");
			String memberPassword = rs.getString("password");
			String memberName = rs.getString("name");
				
			System.out.println(memberId);
				
			mb.setId(memberId);
			mb.setPassword(memberPassword);	
			mb.setName(memberName);
            
		}
	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} finally {	
		...생략           
	}

	return mb;
}

 

모든 DTO 읽기(ArrayList<DTO> / while)

public ArrayList<member_dto> getAllMember() {
	ArrayList<member_dto> arr = new ArrayList<member_dto>();
	PreparedStatement pstmt = null;
	ResultSet rs = null;
	String sql = null;
	//데이터베이스 연결
	Connection conn = dbconn();
	try {
		//SQL전송
		sql = "select * from test01";
		pstmt = conn.prepareStatement(sql);
		rs = pstmt.executeQuery();
		//ResultSet을 객체로 전환
		while(rs.next()) {
			String memberId = rs.getString("id");
			String memberPassword = rs.getString("password");
			String memberName = rs.getString("name");
			
			System.out.println(memberId);
            
			member_dto mb = new member_dto();	
				
			mb.setId(memberId);
			mb.setPassword(memberPassword);	
			mb.setName(memberName);
            
			arr.add(mb);
		}
	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} finally {	
		...생략     
	}

	return arr;
}

 

 

UPDATE

*먼저 컨트롤러에서 member_dto를 생성하고 수정하고 싶은 DTO와 동일한 id를 set해준 다음, password와 name의 변경사항을 set해줘야한다.

public void updateMember(member_dto mb){
    //DB연결
    Connection conn = dbconn();
    PreparedStatement pstmt=null;
    try {
        //SQL 전송
        //update test01 set password=?, name=? where id=?;
        String sql = "UPDATE test01 SET pwd = ?, name = ? WHERE id = ?";
        pstmt = conn.prepareStatement(sql);		
        pstmt.setString(1,mb.getPassword());
        pstmt.setString(2,mb.getName());
	pstmt.setString(3,mb.getId());
        System.out.println(pstmt);
        pstmt.executeUpdate();
        System.out.println("업데이트 완료");

    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
	...생략
    }
}

 

 

DELETE

*DB에서 제거하고싶은 DTO의 id, password, name중 하나가 필요하다.

public void deleteMember(String id){
	Connection conn = dbconn();
	try {
        String sql = "delete from test1 where id=?";
        PreparedStatement pstmt = conn.prepareStatement(sql);
        pstmt.setString(1, id);
        System.out.println(pstmt);
        pstmt.executeUpdate();

    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally{
	...생략
    }
}