DB 연결 메소드

	Connection getConnection() throws ClassNotFoundException, SQLException {
		Class.forName("oracle.jdbc.driver.OracleDriver");
		Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "scott", "tiger");
		return conn;
	}

DAO에 해당 코드로 DB접속 메소드 만들기

 

Connection은 데이터베이스 서버와의 연결을 나타내며, 데이터베이스와의 통신을 위해 JDBC를 사용하여 설정 및 제어하는 데 사용되는 객체

어떤 SQL 문장을 실행시키기 전에 우선 Connection 객체가 있어야 됨 

Connection 객체를 반환하는 이유는 데이터베이스와의 연결을 나타내는 객체를 사용할 수 있도록 하기 위함 

 

완성이 되면 밑에 코드로 DAO에서 만드는 메소드에서 DB 접속 가능

Connection conn = this.getConnection();

 

 

 

ArrayList로 DB 내용 확인 하기

	public ArrayList<ScoreDto> selectList() {
		try {
			Connection conn = this.getConnection();
			ArrayList<ScoreDto> list = new ArrayList<>(); 변수는 조회된 데이터를 담기 위한 리스트
			Statement stmt = conn.createStatement(); 이 객체는 SQL 실행하기 위해 사용
			ResultSet rs = stmt.executeQuery("select num, name, kor, eng, math from score");SELECT문의 결과를 저장하는 객체
			while (rs.next()) { ResultSet 객체의 다음 행으로 이동합니다. 행이 존재하는 동안 반복문을 실행
				int num = rs.getInt("num");메서드를 호출하여 현재 행의 각 열의 값을 가져옵
				String name = rs.getString("name");
				int kor = rs.getInt("kor");
				int eng = rs.getInt("eng");
				int math = rs.getInt("math");
				ScoreDto dto = new ScoreDto(num, name, kor, eng, math);가져온 값을 사용하여 ScoreDto 객체 dto를 생성
				list.add(dto);생성된 dto를 list에 추가
			}
			return list; 반환
		} catch (SQLException | ClassNotFoundException e) {
			e.printStackTrace();
		}
		return null;예외 발생하면 해당 예외를 처리하고 null을 반환

	}

테이블의 데이터를 조회하여 ScoreDto 객체의 리스트를 반환하는 기능을 수행

 

 

총점 ( 리턴 타입, num 참조 )

	public int total(int num) {  num 값과 일치하는 행만을 선택하기 위해 사용
	    int total = 0;  점수의 총합을 저장하기 위한 변수
	    try {
	        Connection conn = this.getConnection();
	        Statement stmt = conn.createStatement();
	        ResultSet rs = stmt.executeQuery("SELECT SUM(kor + eng + math) AS total_score FROM score WHERE num = " + num);
	        if (rs.next()) { rs.next() 메서드를 호출하여 ResultSet 객체의 다음 행으로 이동
            						행이 존재하는 경우, 즉 총합 결과가 존재하는 경우에만 아래의 블록을 실행
	            total = rs.getInt("total_score"); "total_score"라는 별칭을 가진 열의 값을 가져와 total 변수에 저장
	        }
	    } catch (Exception e) {
	        // 예외 처리
	        e.printStackTrace();
	    }
	    return total; 해당 값을 반환 
	}

ScoreServiceImp 클래스에 밑에 코드처럼 메소드를 재정의 해줌 매개변수, return 타입 확인

	public int total(int num) {
		
		return dao.total(num);
	}

마지막으로 JSP에서 호출할 때는 <%=service.total(dto.getNum()) %> 이렇게 호출하면 됨 

service 클래스에 메소드,

매개변수 값으로 dto 클래스에 getNum을 넣어줘야 num을 참조해서 학생별로 총점 계산 가능함 

 

 

 

학생 추가 

	public int insertOne(ScoreDto dto) { 매개변수를 ScoreDto 객체의 필드 값을 사용
		try {
			Connection conn = this.getConnection();
			Statement stmt = conn.createStatement();
			String sql = String.format("insert into score (num,name,kor,eng,math) values (%d, '%s', %d, %d, %d)",
					dto.getNum(), dto.getName(), dto.getKor(), dto.getEng(), dto.getMath());
                    ScoreDto 객체인 dto의 getMath() 메서드를 호출하여 해당 객체의 math 필드 값을 가져오는 코드
                    
			return stmt.executeUpdate(sql); 
            SQL 문을 실행하여 데이터베이스에 영향을 주는 쿼리(INSERT, UPDATE, DELETE)를 실행하고, 실행된 쿼리에 의해 변경된 행의 수를 반환하는 코드
            
		} catch (SQLException | ClassNotFoundException e) {
			e.printStackTrace();
		}
		return 0;// 예외가 발생하면 0을 반환 
	}

 

+ Recent posts