프로그래밍/JSP Servlet

JSP/Servlet – 데이터베이스에 있는 데이터 수정하기

가카리 2016. 4. 17. 19:44
반응형

 

JSP/Servlet – 데이터베이스에 있는 데이터 수정하기

 


2016/04/10 - [프로그래밍/JSP/Servlet] - JSP/Servlet – 데이터베이스에 데이터 입력하기


2016/04/10 - [프로그래밍/JSP/Servlet] - JSP/Servlet – 데이터베이스에서 값 읽어오기



이전 예제에서 만든 데이터베이스를 이용해서 값을 수정해봅시다.

 

바뀐 점은 기존의 쿼리문에서 insert 문 대신 update 문을 사용한 다는 점만 다릅니다.

 

위와 같이 예제를 구성합니다.

 

InitForm.html

 

<!DOCTYPE html>

<html>

<head>

<meta charset="EUC-KR">

<title>Insert title here</title>

</head>

<body>

     <H4>상품 코드를 입력하세요.</H4>

     <FORM ACTION=Reader.jsp METHOD=GET>

         상품 코드 : <INPUT TYPE=TEXT NAME=code SIZE=5>

         <INPUT TYPE=SUBMIT VALUE='확인'>

     </FORM>

</body>

</html>

 

Reader.jsp

 

<%@page import="java.io.UnsupportedEncodingException"%>

<%@ page language="java" contentType="text/html; charset=EUC-KR"

pageEncoding="EUC-KR" errorPage="DBError.jsp" %>

<%@ page import="java.sql.*" %>

 

<%

    String code = request.getParameter("code");//code 값을 가져옴

    if(code == null)

        throw new Exception("상품코드를 입력하세요");

    Connection conn = null;

    Statement stmt = null;

    try{

        Class.forName("com.mysql.jdbc.Driver");

        //데이터 베이스 연결

        conn = DriverManager.getConnection(

                "jdbc:mysql://localhost:3306/webdb", "root", "apmsetup");

        if(conn == null)

            throw new Exception("연결 실패");

        stmt = conn.createStatement();

        

        //코드값을 가지고 쿼리문을 만들어서 실행

        ResultSet rs = stmt.executeQuery(

                "select * from goodsinfo where code = '" + code + "';");

        if(!rs.next())

            throw new Exception("상품코드(" + code + ") 해당하는 자료 없습니다");

        //값을 가져와서 애트리뷰트에 저장함

        String title = rs.getString("title");

        String writer = rs.getString("writer");

        int price = rs.getInt("price");

        request.setAttribute("CODE", code);

        request.setAttribute("TITLE", toUnicode(title));

        request.setAttribute("WRITER", toUnicode(writer));

        request.setAttribute("PRICE", new Integer(price));

        

    }

    finally{

        try{

            stmt.close();

        }

        catch(Exception ignored){

            

        }

        try{

            conn.close();

        }

        catch(Exception ignored){

            

        }

    }

    //결과를 EditForm으로 보내줌

    RequestDispatcher dispatcher = request.getRequestDispatcher("EditForm.jsp");

    dispatcher.forward(request, response);

%>

<%!

    private String toUnicode(String str){//ISO-8859-1문자열을 Unicode 문자열로 바꾸는 메소드

        try{

            byte[] b = str.getBytes("ISO-8859-1");

            return new String(b);

        }

        catch(UnsupportedEncodingException uee){

            System.out.println(uee.getMessage());

            return null;

        }

        

    }

 

%>

<!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>

 

</body>

</html>

 

EditForm.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>

    <H4>상품 정보를 수정하세요</H4>

    <!-- 데이터베이스에서 가져온 값을 뿌려주는 부분 -->

    <FORM ACTION=Updater.jsp METHOD=POST>

        코드 : <INPUT TYPE=TEXT NAME=code SIZE=5

                                    VALUE='${CODE }' READONLY=TRUE><BR>

        제목 : <INPUT TYPE=TEXT NAME=title SIZE=50

                                    VALUE='${TITLE }'> <BR>

        저자 : <INPUT TYPE=TEXT NAME=writer SIZE=20

                                    VALUE='${WRITER }'> <BR>

        가격 : <INPUT TYPE=TEXT NAME=price SIZE=8

                                    VALUE='${PRICE }'> <BR>

        <INPUT TYPE=SUBMIT VALUE='수정'>                            

    </FORM>

</body>

</html>

 

Updater.jsp

 

<%@ page language="java" contentType="text/html; charset=EUC-KR"

pageEncoding="EUC-KR"%>

<%@page import="java.sql.*" %>

<%

    request.setCharacterEncoding("euc-kr");

    //EditForm에서 입력된 값을 가져옴

    String code = request.getParameter("code");

    String title = request.getParameter("title");

    String writer = request.getParameter("writer");

    String price = request.getParameter("price");

    if(code == null || title == null || writer == null || price == null)

        throw new Exception("모든 데이터를 입력해주세요.");

    Connection conn = null;

    Statement stmt = null;

    try{

        Class.forName("com.mysql.jdbc.Driver");

        //데이터 베이스 연결

        conn = DriverManager.getConnection(

                "jdbc:mysql://localhost:3306/webdb", "root", "apmsetup");

        if(conn == null)

            throw new Exception("데이터베이스 연결 실패");

        stmt = conn.createStatement();

        //아래와 같이 쿼리문을 만듬

        String command = String.format("update goodsinfo set " +

                            "title := '%s', writer := '%s', " +

                            "price := '%s' where code = '%s';",

                            title, writer, price, code);

        int rowNum = stmt.executeUpdate(command);

        if(rowNum < 1)

            throw new Exception("입력 실패");

    }

    finally{

        try{

            stmt.close();

        }

        catch(Exception ignored){

        }

        try{

            conn.close();

        }catch(Exception ignored){

            

        }

        //UpdateResult.jsp 실행함 이때 code 값도 get으로 넘겨줌

        response.sendRedirect("UpdateResult.jsp?code=" + code);

    }

%>

<!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>

 

</body>

</html>

 

UpdateResult.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>

    <H4>수정 완료</H4>

    수정된 정보 조회시 아래를 클릭하세요<BR><BR>

    <A HREF=Reader.jsp?code=${param.code }>상품 정보 조회</A>

</body>

</html>

 

 

실행 화면

첫 화면입니다. 상품 코드를 입력하면

상품 정보가 조회되면 수정창이 나옵니다.

아래와 같이 수정완료가 됩니다.

상품 정보 조회 클릭시 다음과 같이 가격이 30000원으로 수정된 것을 알 수 있습니다.

 

 

반응형