본문 바로가기
코딩/수업 정리

21.01.14 Thu [037]

by 6^6 2021. 1. 14.
728x90

복습:

쿼리문에서 mvc_board_seq.nextval;  이게 bId 쪽에 넣어서 bId가 생성할때마다 하나씩 증가시키는것//sql에서 시퀀스 들어가보면 CACHE_SIZE가 20이어서 20번부터 나온다.

 

BDao에서 

SELECT는 executeQuery() (반환값은 ResultSet)으로 ,

INSERT UPDATE DELETE는 executeUpdate() (반환값은 X)로, - why? 결과집합이 없으니까 결과가 몇개로 영향을 받았는지 알려주는 Integer로 반환. - 그럼 while(rs.next())없어도되고, 쿼리문을 insert로 맨위에 변수 준비.

 

executeQuery 랑 executeUpdate 두개 차이만 이해!!

 

 

CTEATE ARTER은 ....

 

===============

<뉴렉 JDBC 09 데이터입력하기와 PreparedStatement부분>

select가 아닌

write, modify,delete의 경우엔 

 

(일단 id, hit, date는 사용자가 쓰는 단어가 아니다. 쿼리문에 안써줘도됨???? )

String ~ = ;

String ~ = ;

String sql = "insert into EMP ( String~ ,String ~ ) values (?,?);

preparedStatement = con.prepare Statement(sql); ( 미리입력값을 준비하겠다는 뜻)

st.setString(1,title); //1은 인덱스값

st.setString(2, ~)

 

그다음 실행하는 execute (단,sql execute는 사용x. why? 이미 갖고있기 때문!)

따라서 executeUpdate();를 쓴다.

st.close(); con.close();해주면 끝!

===================

step(세로), indent(가로)정리

 

 

============================

↓result값 return으로 반환할때 0으로 반환하면 정보입력실패, 1으로 반환하면 정보입력 성공으로 출력되게 하는방법

게시판 최종 여기 참고하기

velog.io/@dnjstjq25/JSP%EC%A0%95%EB%A6%AC-11%EC%9D%BC%EC%B0%A8

게시판 이어서..

 

 

reply부분 만들기

 

controller에서 먼저 reply 생성

[BFrontController.java]
		} else if (com.equals("/reply_view.do")) {
			// write.do에서 넘어오는거만듦
			command = new BReplyViewCommand();
			command.execute(request, response);
			viewPage = "/reply_view.jsp";
			
		}
		else if(com.equals("/reply.do")) {
	         command = new BReplyCommand();
	         command.execute(request, response);
	         viewPage = "list.do";
	      }
          //viewPage의 값이 jsp로 끝나면 UI화면을 띄워주고
		//do로 끝나면 커맨드를 생성하여 적절한 로직을 실행 후 list.do로 포워딩한다
[BDao.java] -- replyShape부분은 아직 추가 안됨. 밑에 소스있음
public BDto reply_view(String bId) {
		// 글 받아오는거라 contentview랑 똑같다.
		BDto dtos = null;
		Connection connection = null;
		PreparedStatement preparedStatement = null;
		ResultSet resultSet = null;

		try {
			connection = dataSource.getConnection();

			String query = "select * from mvc_board where bId =?";
			// 쿼리도 contentview랑 똑같.

			preparedStatement = connection.prepareStatement(query);

			preparedStatement.setInt(1, Integer.parseInt(bId)); // bId가 int여서 1로주고 파싱하기
			// 이렇게 쓰면 위에 ?에 자동으로 1이 들어간다.

			resultSet = preparedStatement.executeQuery();

			while (resultSet.next()) {
				int id = resultSet.getInt("bId");
				// 위에 bid있으니까 id로 수정
				String bName = resultSet.getString("bName");
				String bTitle = resultSet.getString("bTitle");
				String bContent = resultSet.getString("bContent");
				Timestamp bDate = resultSet.getTimestamp("bDate");
				int bHit = resultSet.getInt("bHit");
				int bGroup = resultSet.getInt("bGroup");
				int bStep = resultSet.getInt("bStep");
				int bIndent = resultSet.getInt("bIndent");

				dtos = new BDto(id, bName, bTitle, bContent, bDate, bHit, bGroup, bStep, bIndent);
			}

		} catch (Exception e) {

			e.printStackTrace();
		} finally {
			try {
				if (resultSet != null)
					resultSet.close();
				if (preparedStatement != null)
					preparedStatement.close();
				if (connection != null)
					connection.close();
			} catch (Exception e2) {

				e2.printStackTrace();
			}
		}
		return dtos;
	}

	public void reply(String bId, String bName, String bTitle, String bContent, String bGroup, String bStep,
			String bIndent) {
		// write랑 똑같
		Connection connection = null;
		PreparedStatement preparedStatement = null;// result필요없이 insert다.

		try {
			connection = dataSource.getConnection();

			String query = "insert into mvc_board (bId, bName, bTitle, bContent, bGroup, bStep, bIndent) values (mvc_board_seq.nextval, ?, ?, ?, ?, ?, ?)";
			preparedStatement = connection.prepareStatement(query);

			preparedStatement.setString(1, bName);
			preparedStatement.setString(2, bTitle);
			preparedStatement.setString(3, bContent);
			
			// ↓bGroup, bStep, bIndent를 어떻게 구현할것인지????
			// 댓글달땐 원본글기준, 그 대댓달땐 댓글기준.-기준을 그대로 끌고온다.(bGroup)
			// 댓글달땐 원본글기준으로 밑에 달리고, 그 대댓달땐 댓글기준 밑에달림.(bStep=세로) +1해준다
			// 댓글달땐 원본글기준으로 가로로 한칸 밀림, 그 대댓달땐 댓글기준으로 가로로 한칸 밀린다.(bIndent=가로) +1해준다
			preparedStatement.setInt(4, Integer.parseInt(bGroup));
			preparedStatement.setInt(5, Integer.parseInt(bStep) + 1);
			preparedStatement.setInt(6, Integer.parseInt(bIndent) + 1);

			int rn = preparedStatement.executeUpdate();

			System.out.println("reply 결과" + rn);

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (preparedStatement != null)
					preparedStatement.close();
				if (connection != null)
					connection.close();
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
	}
[BReplyViewCommand.java]
package edu.bit.ex.command;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import edu.bit.ex.dao.BDao;
import edu.bit.ex.dto.BDto;

public class BReplyViewCommand implements BCommand {

	@Override
	public void execute(HttpServletRequest request, HttpServletResponse response) {
	//원본글을 먼저 뿌린다음에 수정
		String bId = request.getParameter("bId");
		
		//원본글 수정해야하니까 가져오기
		BDao dao = new BDao();
		BDto dto = dao.reply_view(bId);
		request.setAttribute("reply_view",dto);

	}
}
[BReplyCommand.java]
package edu.bit.ex.command;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import edu.bit.ex.dao.BDao;

public class BReplyCommand implements BCommand {

	@Override
	public void execute(HttpServletRequest request, HttpServletResponse response) {
		// 원본글작성할땐 bId, bName, bTitle 세개만 필요했음.
		// bName,bTitle, bContent는 원본글/ bGroup, bStep, bIndent는 답변관련

		String bId = request.getParameter("bId");
		String bName = request.getParameter("bName");
		String bTitle = request.getParameter("bTitle");
		String bContent = request.getParameter("bContent");
		String bGroup = request.getParameter("bGroup");
		String bStep = request.getParameter("bStep");
		String bIndent = request.getParameter("bIndent");

		BDao dao = new BDao();
		dao.reply(bId, bName, bTitle, bContent, bGroup, bStep, bIndent);
	}
}
[reply_view.jsp]
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>Insert title here</title>
</head>
<body>

   <table width="500" cellpadding="0" cellspacing="0" border="1">
      <form action="reply.do" method="post">
      
      <!-- 이렇게 hidden하게 되면 안보임. 유저한테 안보이게 숨기려면 이렇게 해야함. -->
         <input type="hidden" name="bId" value="${reply_view.bId}">
         <input type="hidden" name="bGroup" value="${reply_view.bGroup}">
         <input type="hidden" name="bStep" value="${reply_view.bStep}">
         <input type="hidden" name="bIndent" value="${reply_view.bIndent}">
         <tr>
            <td> 번호 </td>
            <td> ${reply_view.bId} </td>
         </tr>
         <tr>
            <td> 히트 </td>
            <td> ${reply_view.bHit} </td>
         </tr>
         <tr>
            <td> 이름 </td>
            <td> <input type="text" name="bName" value="${reply_view.bName}"></td>
         </tr>
         <tr>
            <td> 제목 </td>
            <td> <input type="text" name="bTitle" value="${reply_view.bTitle}"></td>
         </tr>
         <tr>
            <td> 내용 </td>
            <td> <textarea rows="10"  name="bContent">${reply_view.bContent}</textarea></td>
         </tr>
         <tr >
            <td colspan="2"><input type="submit" value="답변"> <a href="list.do" >목록</a></td>
         </tr>
      </form>
   </table>
   
</body>
</html>

 

댓글달때 앞에 -, -- 이렇게 생기는 부분은 어느곳에서 구현?

[list.jsp]파일에서

  <c:forEach begin="1" end="${dto.bIndent}">-</c:forEach> 에서 구현.

 

 

 

 

↓이렇게 20번대로 글번호가 넘어가는거 오류 해결.

이부분 안쓰면 정렬이 안됨. 

[BDao.java] 에 추가
public void reply(String bId, String bName, String bTitle, String bContent, String bGroup, String bStep,
		String bIndent) {

	replyShape(bGroup, bStep);//reply에 이 부분 추가하고,
	}


//이 부분추가
//답변달고자하는거에대해서 끌고와야하기때문에 원본을끌고온다. 댓글은 원문, 대댓은 댓글.
private void replyShape(String strGroup, String strStep) {
		// TODO Auto-generated method stub
		Connection connection = null;
		PreparedStatement preparedStatement = null;

		try {
			connection = dataSource.getConnection();
			String query = "update mvc_board set bStep = bStep + 1 where bGroup = ? and bStep > ?";
            //쿼리문 설명 : 원문에서 bStep+1 해준다.
			preparedStatement = connection.prepareStatement(query);
			preparedStatement.setInt(1, Integer.parseInt(strGroup));
			preparedStatement.setInt(2, Integer.parseInt(strStep));

			int rn = preparedStatement.executeUpdate();
            System.out.println("reply 결과" + rn);
            
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		} finally {
			try {
				if (preparedStatement != null)
					preparedStatement.close();
				if (connection != null)
					connection.close();
			} catch (Exception e2) {
				// TODO: handle exception
				e2.printStackTrace();
			}
		}

	}

 

 

 

 

 

 

 

UPDATE 부분

-sql부분 무조건 외우기.

삭제했을때 step, indent부분 잘 고려해야함.

 

 

HIT 부분

public void upHit(String bId) {
		Connection connection = null;
		PreparedStatement preparedStatement = null;
//제목을 클릭하게되면 bHit+1이 된다. content_view눌렀는데 bid랑 같은숫자이면 bHit+1
		//그럼 content_view쪽에 이 부분을 넣어줘야한다.
		try {
			connection = dataSource.getConnection();

			String query = "update mvc_board set bHit = bHit + 1 where bId=?";

			preparedStatement = connection.prepareStatement(query);
			preparedStatement.setString(1, bId);//이걸넣어야 실행이 된다!!!!

			int rn = preparedStatement.executeUpdate();
			System.out.println("hit 결과" + rn);

		} catch (Exception e) {

			e.printStackTrace();
		} finally {
			try {
				if (preparedStatement != null)
					preparedStatement.close();
				if (connection != null)
					connection.close();
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
	}
public BDto contentView(String bId) {

		upHit(bId); // 조회수 hit 구현 -- 이 부분 추가
}

 

 

 

 

 

 

 

 

서브쿼리

다중처리는 in

//연봉을 3000이상 받는 사원이 소속된 부서와 동일한 부서에서 근무하는 사원들의 정보를 출력하는 쿼리문
SELECT ENAME, SAL, DEPTNO FROM EMP 
WHERE DEPTNO 
IN (SELECT DISTINCT DEPTNO FROM EMP WHERE SAL >= 3000);

 

 

각 부서의 최대 급여를 받는 사람의 부서코드, 이름, 급여를 출력하는데 부서코드 순으로 오름차순 정력하여 출력하는 쿼리
select deptno, ename, sal from emp
where sal in(select max(sal) from emp Group by deptno)order by deptno asc;

//각 부서 라는 얘기 있으면 group by 생각하기.

 

 

 

any는 범위를 따지는 문

select * from emp where sal < any (select sal from emp where deptno=30);
//max값
select ename, sal from emp where sal> all (select sal from emp where deptno=30);

//min값
select ename, sal from emp where sal< all (select sal from emp where deptno=30);

 

select ename, empno, deptno from emp 
where deptno in(select deptno from emp where ename like '%T%');
//KING에게 보고하는 모든 사원의 이름과 급여를 출력하라
select ename, sal, mgr from emp
where ename in(select ename from emp 
where mgr in(select empno from emp where ename like 'KING'));

//선생님 풀이
select ename, sal from emp where mgr=(select empno from emp where enam='KING');

 

//커미션받는 사원과 급여가 일치하는 사원의 이름과 급여를 출력하라
SELECT ENAME, DEPTNO, SAL
FROM EMP
WHERE SAL IN(SELECT SAL
  FROM EMP
  WHERE COMM IS NOT NULL);

 

 

오늘의 문제

1.게시판 설계도를 그리시오(Model 2, MVC)?


2. DB관련하여 아래를 정리하시오.
-게시판 DB설계 (특히 댓글 관련 컬럼)
-list 뽑아내는 sql
-댓글달기 위한 sql
-수정 sql
-게시판 글 insert sql

3.servlet에서 forward 방법은?
RequestDispatcher dispatcher = request.getRequestDispatcher(viewPage);
dispatcher.forward(request, response); 

4.게시판을 두시간 정도로 짤수 있도록 노력합시다.

5. 모르는 부분은 선생님한테 질문할것

6.아래 쿼리를 푸시오
--43> 자신의 급여가 평균 급여보다 많고 이름에 T가 들어가는 사원과
 동일한 부서에 근무하는 모든 사원의 사원 번호, 이름 및 급여를 출력하라.

select empno, ename, sal from emp 
where sal>(select avg(sal) from emp) and deptno 
in(select deptno from emp where ename like '%T%');  

 


7.
--45> Dallas에서 근무하는 사원과 직업이 일치하는 사원의 이름,부서이름, 및 급여를 출력하시오

select e.ename, d.dname, e.sal from emp e, dept d where e.deptno=d.deptno
and e.job in(select e.job from emp e, dept d where e. deptno=d.deptno
and d.loc='DALLAS');

 

 

1.게시판 댓글 달기 위한 SQL 구문(3개)들을 설명하시오.(반드시 이해 할것)
-list를 표현하기 위한 쿼리
"select * from mvc_board where bId = ?"
(reply_view) bId값에 해당하는 원본글을 불러옴

-shapeReply 함수의 쿼리
"update mvc_board set bStep = bStep + 1 where bGroup = ? and bStep > ?"
답글을 저장할 때의 양식.
set bStep = bStep + 1 : 답글이 달릴 때마다 원본글로부터 한 칸씩 내려감
where bGroup = ? and bStep > ? : 
답변을 달기로 한 "원본글"을 기준으로 원본글과 그룹이 같고 원본글의 step(=0)보다 스텝이 큰 기존글들의 스텝을 증가시킴.
(기존글은 모두 원본글보다 step이 큼)
(reply함수에서 원본글 밑에 생성되는 최초의 댓글은 step이 1이게끔 설정함.)
그래야 지금 생성되는 글 밑으로 이전 생성글들이 밀리니까.

-댓글 insert 
replyShape(bGroup, bStep); -> step 조정

-댓글 insert 쿼리
"insert into mvc_board (bId, bName, bTitle, bContent, bGroup, bStep, bIndent) "
               + "values (mvc_board_seq.nextval, ?, ?, ?, ?, ?, ?)"
새로 입력한 답글 값을 저장

===========================================
group: 원본글의 그룹 넘버. 원본글과 답변글을 모두 묶은 id값.
step: 원본글로부터 몇 번째 아래에 답변글이 있는지를 표시.
indent: 얼마만큼 안쪽으로 글이 들어가서 시작할 것인지를 표시.
===========================================

 

728x90

'코딩 > 수업 정리' 카테고리의 다른 글

21.01.18 [039] Mon  (0) 2021.01.18
21.01.15 [038] Fri  (0) 2021.01.15
21.01.13 Wed [036]  (0) 2021.01.13
21.01.12 Tue [035]  (0) 2021.01.12
21.01.11 Mon [034]  (0) 2021.01.11

댓글