본문 바로가기

Java, Spring/06일

6일차 03

일단 DB에 값을 넣고 빼고를 해보자..

DB하나 만들어보자..

oracle.sql 열어서 테이블 하나 만들자..

CREATE TABLE BOARD ( 
seq         number             primary key,    --글번호 
title         varchar2(100)     not null,         --글제목 
name         varchar2(30)     not null,         --작성자 
password     varchar2(30)     not null,         --비밀번호 
content     varchar2(4000)     not null,         --내용 
readcount     number             default 0,         --조회수 
writeday     date            default sysdate    --날짜 
);

commit 
create sequence boardseq start with 1 nocache;

alt+x 로 실행..

nocache 안주면 오라클이 미리 메모리에 20개씩 까놔.. 서버껐다키면 2에서 22로 뛰어..

 

WebContent 밑에 board폴더 만들고

insert.jsp 만든다. (입력폼)

 

 
<%@ page language="java" contentType="text/html; charset=UTF-8" 
    pageEncoding="UTF-8"%> 
<!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=UTF-8"> 
<title>Insert title here</title> 
</head> 
<body> 
<form action="insert_action.jsp" method="post"> 
<table> 
<tr>    
    <th>제목</th> 
    <td><input type="text" name = "title" /></td> 
</tr> 
<tr>    
    <th>이름</th> 
    <td><input type="text" name = "name" /></td> 
</tr> 
<tr>    
    <th>비밀번호</th> 
    <td><input type="password" name = "password" /></td> 
</tr> 
<tr>    
    <th>내용</th> 
    <td><textarea cols="50" rows="5" name = "content" /></textarea></td> 
</tr> 
<tr> 
    <td colspan="2" aligh="center"> 
        <input type="submit" value = "작성완료" /></td> 
    </td> 
</tr> 
</table> 
</form> 
</body> 
</html>

입력한 값을 Post방식으로 insert_action.jsp에 전달..

웹브라우저로 띄워서 보기 : Windows메뉴->Web Browser->에서 선택

 

insert_action.jsp에 잘 넘어오나 한번 확인해보자

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%
	String name = request.getParameter("name");
	String title = request.getParameter("title");
	String password = request.getParameter("password");
	String content = request.getParameter("content");
%>
<!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=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<%=name%><br />
	<%=title%><br />
	<%=password%><br />
	<%=content%><br />
</body>
</html>

 

이제 DB에 넣어보자..

삽입, 삭제, 수정에는 ResultSet이 필요없겠지..

<%@page import="java.sql.*"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
    String name = request.getParameter("name");
    String title = request.getParameter("title");
    String password = request.getParameter("password");
    String content = request.getParameter("content");
%>    
<!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=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
    Connection cn = null;

    Statement st = null;
    String sql = "insert into board (seq, title, name, password, content) " +
            "values(boardseq.nextval, '" 
            + title + "', '" + name + "', '" + password + "', '" + content + "')";
    
    boolean result = false;
    
    try {
        Class.forName("oracle.jdbc.OracleDriver");        //드라이버 있는지 확인
        cn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "oraclejava", "oraclejava");
        
        st = cn.createStatement();
        if (st.executeUpdate(sql) > 0 ) result = true; //executeUpdate(sql);    //영향받은 레코드수 리턴
        
    } catch (Exception e){
        e.printStackTrace();
    } finally {
        if (st!= null) try { st.close(); } catch(Exception e) {}
        if (cn!= null) try { cn.close(); } catch(Exception e) {}
        
    }         
    if (result == true)
        System.out.println("잘 입력되었습니다.");
    else
        System.out.println("입력실패입니다.");     
%>
</body>
</html>

 

dynamic query vs parameter query
dynamic query : 작성하기 불편, SQL injection에 취약. 기존에 날린 쿼리인지 인식못해

오라클에서 비용이 제일 많이 발생하는것은 보조기억장치에서 우리가 원하는 데이터를 찾아 메모리에 올리는것이고 그 다음이 날라온 명령어가 어떤 내용인지 오라클 옵티마이저가 파싱해서 인식하는것이다.

문자열로 결합해 날리면 기존의 쿼리인지 인식 못해.

 

parameter query : 작성이 편해, SQL injection 방지, 오라클 옵티마이저가 기존의 쿼리로 인식해서 성능에 좋아.

 

-> PreparedStatement로 변경..

<%@page import="java.sql.*"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
    String name = request.getParameter("name");
    String title = request.getParameter("title");
    String password = request.getParameter("password");
    String content = request.getParameter("content");
%>    
<!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=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
    Connection cn = null;

    PreparedStatement st = null;
    String sql = "insert into board (seq, title, name, password, content) " +
            "values (boardseq.nextval, ?, ?, ?, ?)";
    
    boolean result = false;
    
    try {
        Class.forName("oracle.jdbc.OracleDriver");        //드라이버 있는지 확인
        cn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "oraclejava", "oraclejava");
        
        st = cn.prepareStatement(sql);    //오라클에 쿼리 먼저 던져놔..
        st.setString(1, title);
        st.setString(2, name);
        st.setString(3, password);
        st.setString(4, content);
        
        if (st.executeUpdate() > 0 ) result = true; //영향받은 레코드수 리턴    
        
    } catch (Exception e){
        e.printStackTrace();
    } finally {
        if (st!= null) try { st.close(); } catch(Exception e) {}
        if (cn!= null) try { cn.close(); } catch(Exception e) {}        
    }        

%>
<script>
alert('<%= result == true ? "글이 입력되었습니다." : "글 입력 실패" %>');
location.href='<%= result == true ? "list.jsp" : "javascript:history.back();" %>';
</script>
</body>
</html>

주의
PreparedStatement st = null;
st = cn.prepareStatement(sql);

 

잘 입력이 되지?

'Java, Spring > 06일' 카테고리의 다른 글

6일차 01  (0) 2012.09.20
6일차 02  (0) 2012.09.20
6일차 04  (0) 2012.09.20
6일차 05  (0) 2012.09.20