이안의 평일코딩

Oracle 9일차 - DML(Data Manipulation Language) 본문

Back-end/Oracle

Oracle 9일차 - DML(Data Manipulation Language)

이안92 2020. 8. 14. 10:22
반응형

2020.08.14(금)

1. DML

 = INSERT (데이터 추가)

    형식)

     1) 전체 추가

        INSERT INTO table_name VALUES(값, 값..)

         => 문자, 날짜 => ''

         => 데이터베이스 순서대로 입력

     2) 원하는 데이터만 추가

        INSERT INTO table_name(컬럼명, 컬럼명..) VALUES(값, 값..)

     3) 다른 테이블에 있는 데이터 전체를 추가

        INSERT INTO table_name SELECT * FROM table_name

     4) 같은 데이터를 여러 테이블에 저장

        INSERT ALL

 = UPDATE (데이터 수정)

    UPDATE table_name SET

    컬럼명 = 변경할 값, 컬럼명 = 변경할 값...

    ===============================> 전체 데이터가 변경

    [WHERE 조건]

 = DELETE (데이터 삭제)

    DELETE FROM table_name => 전체 데이터가 삭제

    [WHERE 조건]

 ================== 활용 (게시판)

 = MERGE (데이터 병합)

 

 

*1) INSERT 연습

-- 테이블 COPY

-- 데이터는 복사하지 않고 테이블 형태만 복사 => 조건 (false)

CREATE TABLE dept_test AS SELECT * FROM dept WHERE 1=2;

 

-- 데이터 추가

-- 전체 => deptno(NUMBER(2)), dname(VARCHAR2(2)), loc(VARCHAR2(10))

INSERT INTO dept_test VALUES(50, '영업부', '서울');

 

INSERT, UPDATE, DELETE => ROLLBACK; 되돌리기 COMMIT; 메모리저장

 

-- 부분적으로 추가

INSERT INTO dept_test(deptno,dname) VALUES(70, '총무부');

 

-- 전체 추가

SQL> INSERT ALL INTO dept_test1 VALUES(deptno, dname, loc)
  2  INTO dept_test2 VALUES(deptno, dname, loc)
  3  SELECT * FROM dept;

8 rows created.

SQL> select * FROM dept_test1;

    DEPTNO DNAME                        LOC
---------- ---------------------------- --------------------------
        10 ACCOUNTING                   NEW YORK
        20 RESEARCH                     DALLAS
        30 SALES                        CHICAGO
        40 OPERATIONS                   BOSTON

SQL> select * FROM dept_test2;

    DEPTNO DNAME                        LOC
---------- ---------------------------- --------------------------
        10 ACCOUNTING                   NEW YORK
        20 RESEARCH                     DALLAS
        30 SALES                        CHICAGO
        40 OPERATIONS                   BOSTON

 

-- AS없이 형식만 맞으면 들어감

INSERT INTO dept_test SELECT * FROM dept;

 

-- 입사일 1~3월 => emp1, 4~6월 => emp2, .... 10~12월 => emp4

SQL> CREATE TABLE emp1 AS SELECT * FROM emp WHERE 1=2;

Table created.

SQL> CREATE TABLE emp2 AS SELECT * FROM emp WHERE 1=2;

Table created.

SQL> CREATE TABLE emp3 AS SELECT * FROM emp WHERE 1=2;

Table created.

SQL> CREATE TABLE emp4 AS SELECT * FROM emp WHERE 1=2;

Table created.

SQL> desc emp1;
 Name                                                                                                              Null?    Type
 ----------------------------------------------------------------------------------------------------------------- -------- ----------------------------------------------------------------------------
 EMPNO                                                                                                                      NUMBER(4)
 ENAME                                                                                                                      VARCHAR2(10)
 JOB                                                                                                                        VARCHAR2(9)
 MGR                                                                                                                        NUMBER(4)
 HIREDATE                                                                                                                   DATE
 SAL                                                                                                                        NUMBER(7,2)
 COMM                                                                                                                       NUMBER(7,2)
 DEPTNO                                                                                                                     NUMBER(2)

SQL> INSERT ALL WHEN SUBSTR(hiredate, 4, 2) BETWEEN '01' AND '03' THEN INTO emp1 VALUES(empno, ename, job, mgr, hiredate, sal, comm, deptno) SELECT * FROM emp;

4 rows created.

SQL> INSERT ALL WHEN SUBSTR(hiredate, 4, 2) BETWEEN '04' AND '06' THEN INTO emp2 VALUES(empno, ename, job, mgr, hiredate, sal, comm, deptno) SELECT * FROM emp;

3 rows created.

SQL> INSERT ALL WHEN SUBSTR(hiredate, 4, 2) BETWEEN '07' AND '09' THEN INTO emp3 VALUES(empno, ename, job, mgr, hiredate, sal, comm, deptno) SELECT * FROM emp;

2 rows created.

SQL> INSERT ALL WHEN SUBSTR(hiredate, 4, 2) BETWEEN '10' AND '12' THEN INTO emp4 VALUES(empno, ename, job, mgr, hiredate, sal, comm, deptno) SELECT * FROM emp;

5 rows created.

SQL> SELECT * FROM emp1;

     EMPNO ENAME                JOB                       MGR HIREDATE        SAL       COMM     DEPTNO
---------- -------------------- ------------------ ---------- -------- ---------- ---------- ----------
      7499 ALLEN                SALESMAN                 7698 81/02/20       1600        300         30
      7521 WARD                 SALESMAN                 7698 81/02/22       1250        500         30
      7876 ADAMS                CLERK                    7788 83/01/12       1100                    20
      7934 MILLER               CLERK                    7782 82/01/23       1300                    10

SQL> SELECT * FROM emp2;

     EMPNO ENAME                JOB                       MGR HIREDATE        SAL       COMM     DEPTNO
---------- -------------------- ------------------ ---------- -------- ---------- ---------- ----------
      7566 JONES                MANAGER                  7839 81/04/02       2975                    20
      7698 BLAKE                MANAGER                  7839 81/05/01       2850                    30
      7782 CLARK                MANAGER                  7839 81/06/09       2450                    10

SQL> SELECT * FROM emp3;

     EMPNO ENAME                JOB                       MGR HIREDATE        SAL       COMM     DEPTNO
---------- -------------------- ------------------ ---------- -------- ---------- ---------- ----------
      7654 MARTIN               SALESMAN                 7698 81/09/28       1250       1400         30
      7844 TURNER               SALESMAN                 7698 81/09/08       1500                    30

SQL> SELECT * FROM emp4;

     EMPNO ENAME                JOB                       MGR HIREDATE        SAL       COMM     DEPTNO
---------- -------------------- ------------------ ---------- -------- ---------- ---------- ----------
      7369 SMITH                CLERK                    7902 80/12/17        800                    20
      7788 SCOTT                ANALYST                  7566 82/12/09       3000                    20
      7839 KING                 PRESIDENT                     81/11/17       5000                    10
      7900 JAMES                CLERK                    7698 81/12/03        950                    30
      7902 FORD                 ANALYST                  7566 81/12/03       3000                    20

 

--필요한 컬럼만 가져와서 테이블 생성

SQL> CREATE TABLE emp_update(empno, ename, job, sal) AS SELECT empno, ename, job, sal FROM emp;

Table created.

SQL> select * FROM emp_update;

     EMPNO ENAME                JOB                       SAL
---------- -------------------- ------------------ ----------
      7369 SMITH                CLERK                     800
      7499 ALLEN                SALESMAN                 1600
      7521 WARD                 SALESMAN                 1250
      7566 JONES                MANAGER                  2975
      7654 MARTIN               SALESMAN                 1250
      7698 BLAKE                MANAGER                  2850
      7782 CLARK                MANAGER                  2450
      7788 SCOTT                ANALYST                  3000
      7839 KING                 PRESIDENT                5000
      7844 TURNER               SALESMAN                 1500
      7876 ADAMS                CLERK                    1100
      7900 JAMES                CLERK                     950
      7902 FORD                 ANALYST                  3000
      7934 MILLER               CLERK                    1300

14 rows selected.

 

 

--2) UPDATE 연습

SQL> UPDATE emp_update SET sal = 3500;

14 rows updated.

SQL> select * FROM emp_update;

     EMPNO ENAME                JOB                       SAL
---------- -------------------- ------------------ ----------
      7369 SMITH                CLERK                    3500
      7499 ALLEN                SALESMAN                 3500
      7521 WARD                 SALESMAN                 3500
      7566 JONES                MANAGER                  3500
      7654 MARTIN               SALESMAN                 3500
      7698 BLAKE                MANAGER                  3500
      7782 CLARK                MANAGER                  3500
      7788 SCOTT                ANALYST                  3500
      7839 KING                 PRESIDENT                3500
      7844 TURNER               SALESMAN                 3500
      7876 ADAMS                CLERK                    3500
      7900 JAMES                CLERK                    3500
      7902 FORD                 ANALYST                  3500
      7934 MILLER               CLERK                    3500
      
      ROLLBACK;
      
SQL> UPDATE emp_update SET sal=3200 WHERE job = 'MANAGER';

	3 rows updated.

SQL> select * FROM emp_update;

     EMPNO ENAME                JOB                       SAL
---------- -------------------- ------------------ ----------
      7369 SMITH                CLERK                     800
      7499 ALLEN                SALESMAN                 1600
      7521 WARD                 SALESMAN                 1250
      7566 JONES                MANAGER                  3200
      7654 MARTIN               SALESMAN                 1250
      7698 BLAKE                MANAGER                  3200
      7782 CLARK                MANAGER                  3200
      7788 SCOTT                ANALYST                  3500
      7839 KING                 PRESIDENT                5000
      7844 TURNER               SALESMAN                 1500
      7876 ADAMS                CLERK                    1100
      7900 JAMES                CLERK                     950
      7902 FORD                 ANALYST                  3000
      7934 MILLER               CLERK                    1300

14 rows selected.

SQL> UPDATE emp_update SET sal=3200, job='M' WHERE job = 'MANAGER';

                                          =========== 동시에 여러개도 바꿀 수 있음

 

-- 3) DELETE 연습

DELETE FROM table_name;

SQL> DELETE FROM emp_update;

14 rows deleted.

SQL> ROLLBACK;

Rollback complete.

SQL> DELETE FROM emp_update WHERE ename='SCOTT';

1 row deleted.

SQL> DELETE FROM emp_update WHERE ename LIKE 'A%';

2 rows deleted.

SQL> SELECT * FROM emp_update;

     EMPNO ENAME                JOB                       SAL
---------- -------------------- ------------------ ----------
      7369 SMITH                CLERK                     800
      7521 WARD                 SALESMAN                 1250
      7566 JONES                MANAGER                  2975
      7654 MARTIN               SALESMAN                 1250
      7698 BLAKE                MANAGER                  2850
      7782 CLARK                MANAGER                  2450
      7839 KING                 PRESIDENT                5000
      7844 TURNER               SALESMAN                 1500
      7900 JAMES                CLERK                     950
      7902 FORD                 ANALYST                  3000
      7934 MILLER               CLERK                    1300

 

 

2. 게시판 만들기

SQL> CREATE TABLE freeboard(
  2   no NUMBER,
  3   name VARCHAR2(34),
  4   subject VARCHAR2(2000),
  5   content CLOB,
  6   pwd VARCHAR2(10),
  7   regdate DATE DEFAULT SYSDATE,
  8   hit NUMBER DEFAULT 0
  9  );

Table created.

regdate, hit 기본값으로 쓸 때 지정해주지 않으면 에러발생

SQL> INSERT INTO freeboard VALUES(1, '홍길동', '자유게시판 만들기', 'CURD~~', '1234');
INSERT INTO freeboard VALUES(1, '홍길동', '자유게시판 만들기', 'CURD~~', '1234')
            *
ERROR at line 1:
ORA-00947: not enough values

지정 (no, name, subject, content, pwd)해주면 나머지 regdate, hit은 설정해둔 DEFAULT 값을 넣음(SYSDATE, 0)

SQL> INSERT INTO freeboard(no, name, subject, content, pwd) VALUES(1, '홍길동', '자유게시판 만들기', 'CURD~~', '1234');

1 row created.

SQL> SELECT * FROM freeboard;

        NO NAME        SUBJECT           CONTENT      PWD      REGDATE   HIT
---------- ---------- ----------------- ------------- -------- --------- -----
         1  홍길동     자유게시판 만들기  CURD~~       1234    20/08/14   0

 

DAO 오라클과 연결

GETTER/SETTER => 캡슐화방식 메소드를 통해서만 접근

 

BoardVO.java

package com.sist.dao;
import java.util.*;
/*
 *   no NUMBER,
     name VARCHAR2(34),
     subject VARCHAR2(2000),
     content CLOB,
     pwd VARCHAR2(10),
     regdate DATE DEFAULT SYSDATE,
     hit NUMBER DEFAULT 0
     
     	문자 =============> 자바 (String)
     		CHAR
     		VARCHAR2
     		CLOB
     	숫자 =============> 자바(int, double)
     		NUMBER => 1,2,3 => int
     		NUMBER(7,2) => 4.5, 10.7 => double
     	날짜 =============> java.util.Date
     		DATE
     		TIMESTAMP
     	기타 =============> InputStream
     		BLOB
     		BFILE
 *
 */
public class BoardVO {
	private int no;
	private String name;
	private String subject;
	private String content;
	private String pwd;
	private Date regdate;
	private int hit;
	
	public int getNo() {
		return no;
	}
	public void setNo(int no) {
		this.no = no;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getSubject() {
		return subject;
	}
	public void setSubject(String subject) {
		this.subject = subject;
	}
	public String getContent() {
		return content;
	}
	public void setContent(String content) {
		this.content = content;
	}
	public String getPwd() {
		return pwd;
	}
	public void setPwd(String pwd) {
		this.pwd = pwd;
	}
	public Date getRegdate() {
		return regdate;
	}
	public void setRegdate(Date regdate) {
		this.regdate = regdate;
	}
	public int getHit() {
		return hit;
	}
	public void setHit(int hit) {
		this.hit = hit;
	}
}

 

* 컴퓨터 <=> 웹서버(tomcat) <=> 자바(DAO:Data Access Object) <=> 오라클

 

BoardDAO.java

package com.sist.dao;
import java.util.*;
import java.sql.*;
public class BoardDAO {
	// 연결
	private Connection conn; // 오라클 연결 클래스
	// SQL문장을 전송
	private PreparedStatement ps;
	// 오라클 주소 첨부
	private final String URL="jdbc:oracle:thin:@localhost:1521:XE";
	// 연결 준비
	// 1. 드라이버 등록
	public BoardDAO() {
		try {
			Class.forName("oracle.jdbc.driver.OracleDriver");
		}catch(Exception ex) {
			System.out.println(ex.getMessage());
		}
	}
	// 2. 연결/닫기 반복 => 기능의 반복일 경우 => 메소드로 처리
	public void getConnection() {
		try {
			conn=DriverManager.getConnection(URL,"hr","happy");
		}catch(Exception ex) {}
	}
	public void disConnection() {
		try {
			if(ps!=null) ps.close();
			if(conn!=null) conn.close();
		}catch(Exception ex) {}
	}
	// 기능
	// 1. 목록 (게시판) => SELECT
	public ArrayList<BoardVO> boardListData() {
		ArrayList<BoardVO> list = new ArrayList<BoardVO>();
		try {
			// 연결
			getConnection();
			// SQL문장 전송
			String sql="SELECT no,subject,name,regdate,hit "
					+"FROM freeboard "
					+"ORDER BY no DESC"; // 최신 등록된 게시물 먼저 출력
					// ORDER BY => 단점(속도가 늦다) => INDEX
			ps=conn.prepareStatement(sql);
			// SQL실행후에 결과값 받기
			ResultSet rs = ps.executeQuery();
			// 결과값을 => ArrayList에 첨부
			while(rs.next()) { // 출력한 첫번째줄부터 마지막줄까지 읽어 온다
				BoardVO vo = new BoardVO();
				vo.setNo(rs.getInt(1));
				vo.setSubject(rs.getString(2));
				vo.setName(rs.getString(3));
				vo.setRegdate(rs.getDate(4));
				vo.setHit(rs.getInt(5));
				list.add(vo);
			}
			rs.close(); // while문 끝나고 rs 닫음
		}catch(Exception ex) {
			System.out.println(ex.getMessage());
		}finally {
			disConnection();
		}
		return list;
	}

	// 2. 내용보기 => SELECT (WHERE) ?no=1
	public BoardVO boardDetail(int no) {
		BoardVO vo = new BoardVO();
		try {
			// 연결
			getConnection();
			// SQL 문장 전송 ==> 조회수 증가
			String sql="UPDATE freeboard SET "
					+"hit=hit+1 "
					+"WHERE no=?";
			ps=conn.prepareStatement(sql);
			ps.setInt(1, no); // ?에 값을 채운다
			// 실행
			ps.executeUpdate();
			
			// 내용물 데이터를 가지고 온다
			sql="SELECT no,name,subject,content,regdate,hit "
			   +"FROM freeboard "
			   +"WHERE no=?";
			ps=conn.prepareStatement(sql);
			ps.setInt(1, no);
			
			ResultSet rs=ps.executeQuery();
			rs.next();
			
			vo.setNo(rs.getInt(1));
			vo.setName(rs.getString(2));
			vo.setSubject(rs.getString(3));
			vo.setContent(rs.getString(4));
			vo.setRegdate(rs.getDate(5));
			vo.setHit(rs.getInt(6));
			
			rs.close();
		}catch(Exception ex) {
			System.out.println(ex.getMessage());
		}finally {
			disConnection();
		}
		return vo;
	}
	// 3. 글쓰기 => INSERT
	public void boardInsert(BoardVO vo) {
		try {
			getConnection();
			// 연결
			// SQL문장 전송 => 실행
			String sql = "INSERT INTO freeboard(no, name, subject, content, pwd) "
					+"VALUES((SELECT NVL(MAX(no)+1,1) FROM freeboard),?,?,?,?)";
			         // 데이터 하나도 없을때 NULL이니 NVL로 시작을 1로 넣어줌
			ps=conn.prepareStatement(sql); // ?에 하나씩 채워준다
			ps.setString(1, vo.getName());
			ps.setString(2, vo.getSubject());
			ps.setString(3, vo.getContent());
			ps.setString(4, vo.getPwd());
			
			ps.executeUpdate(); // COMMIT수행 => INSERT, UPDATE, DELETE 
		}catch(Exception ex) {
			System.out.println(ex.getMessage());
		}finally {
			disConnection();
		}
	}
	// 4. 글수정 => UPDATE
	// 5. 글삭제 => DELETE
	// 6. 찾기 => SELECT (LIKE)
}

 

BoardList.java

package com.sist.board;

import java.io.*;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sist.dao.BoardDAO;
import com.sist.dao.BoardVO;

@WebServlet("/BoardList")
public class BoardList extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 브라우저에서 실행하는 화면 => HTML
		// 브라우저에 알림 => HTML문서를 전송할 것이다
		response.setContentType("text/html;charset=EUC-KR");
		// HTML을 브라우저로 전송 시작
		PrintWriter out = response.getWriter();
		out.println("<html>");
		out.println("<head>");
		out.println("<link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css\">");
		out.println("<style type=text/css>");
		out.println(".row {margin:0px auto; width:700px}");
		out.println("h2 {text-align:center}");
		out.println("</style>");
		out.println("</head>");
		out.println("<body>");
		out.println("<div class=container>");
		out.println("<h2>자유게시판</h2>");
		out.println("<div class=row>");
		
	    out.println("<table class=\"table\">");
	    out.println("<tr>");
	    out.println("<td>");
	    out.println("<a href=BoardInsert class=\"btn btn-lg btn-success\">새글</a>");
	    out.println("</td>");
	    out.println("</tr>");
	    out.println("</table>");
		
		out.println("<table class=\"table table-hover\">");
		out.println("<tr class=info>");
		out.println("<th class=text-center width=10%>번호</th>");
		out.println("<th class=text-center width=45%>제목</th>");
		out.println("<th class=text-center width=15%>이름</th>");
		out.println("<th class=text-center width=20%>작성일</th>");
		out.println("<th class=text-center width=10%>조회수</th>");
		out.println("</tr>");
		// 출력
		BoardDAO dao = new BoardDAO();
		ArrayList<BoardVO> list = dao.boardListData();
		for(BoardVO vo : list) {
			out.println("<tr>");
			out.println("<td class=text-center width=10%>"+vo.getNo()+"</td>");
			out.println("<td class=text-left width=45%>"
			+"<a href=BoardDetail?no="+vo.getNo()+">"
			+vo.getSubject()+"</a></td>");
			out.println("<td class=text-center width=15%>"+vo.getName()+"</td>");
			out.println("<td class=text-center width=20%>"+vo.getRegdate().toString()+"</td>");
			out.println("<td class=text-center width=10%>"+vo.getHit()+"</td>");
			out.println("</tr>");
		}
		  out.println("</table>");
	      out.println("<hr>");
	      
	      out.println("<table class=\"table\">");
	      out.println("<tr>");
	      
	      out.println("<td class=text-left>");
	      out.println("Search:");
	      out.println("<select class=input-sm>");
	      out.println("<option>이름</option>");
	      out.println("<option>제목</option>");
	      out.println("<option>내용</option>");
	      out.println("</select>");
	      out.println("<input type=text size=15 class=input-sm>");
	      out.println("<input type=button value=찾기 class=\"btn btn-sm btn-danger\">");
	      out.println("</td>");
	      
	      out.println("<td class=text-right>");
	      out.println("<a href=BoardInsert class=\"btn btn-lg btn-primary\">이전</a>");
	      out.println("0 page / 0 pages");
	      out.println("<a href=BoardInsert class=\"btn btn-lg btn-primary\">다음</a>");
	      out.println("</td>");
	      
	      
	      out.println("</tr>");

		out.println("</table>");
		out.println("</div>");
		out.println("</div>");
		out.println("</body>");
		out.println("</html>");
	}

}

 

게시물목록 - 새글(BoardInsert, doGet=>입력창, doPost=>데이터베이스 연결),

                 찾기, 내용보기

내용보기 - 수정, 삭제

 

 

BoardInsert

package com.sist.board;

import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sist.dao.BoardDAO;
import com.sist.dao.BoardVO;

@WebServlet("/BoardInsert")
public class BoardInsert extends HttpServlet {
   private static final long serialVersionUID = 1L;
   // 폼 작업
   protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            // 브라우저에 실행하는 화면 => html
            // 브라우저에 알림 => html문서를 전송할 것이다
            response.setContentType("text/html;charset=EUC-KR");
            // HTML을 브라우저로 전송 시작
            PrintWriter out=response.getWriter();
            out.println("<html>");
            out.println("<head>");
            out.println("<link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css\">");
            out.println("<style type=text/css>");
            out.println(".row {margin:0px auto;width:500px;}");
            out.println("h2 {text-align: center;}");
            out.println("</style>");
            out.println("</head>");
            out.println("<body>");
            out.println("<div class=container>");
            out.println("<h2>글쓰기</h2>");
            out.println("<div class=row>");
            
            out.println("<form method=post action=BoardInsert>");
            out.println("<table class=\"table\">");
            out.println("<tr>");
            out.println("<td width=15% class=text-right>이름</td>");
            out.println("<td width=85%>");
            out.println("<input type=text size=15 class=input-sm name=name>");
            out.println("</td>");
            out.println("</tr>");
            
            out.println("<tr>");
            out.println("<td width=15% class=text-right>제목</td>");
            out.println("<td width=85%>");
            out.println("<input type=text size=45 class=input-sm name=subject>");
            out.println("</td>");
            out.println("</tr>");
            
            out.println("<tr>");
            out.println("<td width=15% class=text-right>내용</td>");
            out.println("<td width=85%>");
            out.println("<textarea cols=50 rows=10 name=content></textarea>");
            out.println("</td>");
            out.println("</tr>");
            
            out.println("<tr>");
            out.println("<td width=15% class=text-right>비밀번호</td>");
            out.println("<td width=85%>");
            out.println("<input type=password size=10 class=input-sm name=pwd>");
            out.println("</td>");
            out.println("</tr>");
            
            out.println("<tr>");
            out.println("<td colspan=2 class=text-center>");
            out.println("<input type=submit class=\"btn btn-sm btn-danger\" value=글쓰기>");
            out.println("<input type=button class=\"btn btn-sm btn-info\" value=취소  onclick=\"javascript:history.back()\">");
            out.println("</td>");
            out.println("</tr>");
            
            out.println("</table>");
            out.println("</form>");
            out.println("</div>");
            out.println("</div>");
            out.println("</body>");
            out.println("</html>");
   }

   // 데이터베이스 연결 => 요청처리
   protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      try {
    	  request.setCharacterEncoding("EUC-KR");
      }catch(Exception ex) {}
	  String name = request.getParameter("name");
      String subject = request.getParameter("subject");
      String content = request.getParameter("content");
      String pwd = request.getParameter("pwd");
//      System.out.println("이름:"+name);
//      System.out.println("제목:"+subject);
//      System.out.println("내용:"+content);
//      System.out.println("비번:"+pwd);
      BoardVO vo = new BoardVO();
      vo.setName(name);
      vo.setSubject(subject);
      vo.setPwd(pwd);
      vo.setContent(content);
      
      // DAO로 전송 => 오라클 INSERT
      BoardDAO dao = new BoardDAO();
      dao.boardInsert(vo);
      // 목록으로 이동
      response.sendRedirect("BoardList");
   }
}

 

BoardDetail

package com.sist.board;

import java.io.*;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sist.dao.BoardDAO;
import com.sist.dao.BoardVO;


@WebServlet("/BoardDetail")
public class BoardDetail extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=EUC-KR");
        // HTML을 브라우저로 전송 시작
        PrintWriter out=response.getWriter();
        
        // 번호 받는다 ?no=10
        String no = request.getParameter("no");
        BoardDAO dao = new BoardDAO();
        BoardVO vo = dao.boardDetail(Integer.parseInt(no));
        
        out.println("<html>");
        out.println("<head>");
        out.println("<link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css\">");
        out.println("<style type=text/css>");
        out.println(".row {margin:0px auto;width:600px;}");
        out.println("h2 {text-align: center;}");
        out.println("</style>");
        out.println("</head>");
        out.println("<body>");
        out.println("<div class=container>");
        out.println("<h2>내용보기</h2>");
        
        out.println("<div class=row>");
        out.println("<table class=\"table\">");
        out.println("<tr>");
        out.println("<td class=\"info text-center\" width=25%>번호</td>");
        out.println("<td width=25% class=text-center>"+vo.getNo()+"</td>");
        out.println("<td class=\"info text-center\" width=25%>작성일</td>");
        out.println("<td width=25% class=text-center>"+vo.getRegdate().toString()+"</td>");
        out.println("</tr>");
        
        out.println("<tr>");
        out.println("<td class=\"info text-center\" width=25%>이름</td>");
        out.println("<td width=25% class=text-center>"+vo.getName()+"</td>");
        out.println("<td class=\"info text-center\" width=25%>조회수</td>");
        out.println("<td width=25% class=text-center>"+vo.getHit()+"</td>");
        out.println("</tr>");
        
        out.println("<tr>");
        out.println("<td class=\"info text-center\" width=25%>제목</td>");
        out.println("<td colspan=3>"+vo.getSubject()+"</td>");
        out.println("</tr>");
        
        out.println("<tr>");
        out.println("<td colspan=4 height=200 valign=top>"+vo.getContent()+"</td>");
        out.println("</tr>");
        
        out.println("<tr>");
        out.println("<td colspan=4 class=text-right>");
        out.println("<a href=# class=\"btn btn-s btn-success\">수정</a>");
        out.println("<a href=# class=\"btn btn-s btn-danger\">삭제</a>");
        out.println("<a href=BoardList class=\"btn btn-s btn-warning\">목록</a>");
        out.println("</td>");
        out.println("</tr>");
        
        out.println("</table>");
        out.println("</div>");
        out.println("</div>");
        out.println("</body>");
        out.println("</html>");
	}
}
반응형
Comments