2019.02.01 JDBC: SQL문 사용하기 (INSERT)

2019. 2. 1. 16:53JSP

# INSERT


<DBSM에 저장되어 있는 기존 TABLE>






① insertFrom.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>insertForm</title>
</head>
<body>
    <h1>도시 위치값 입력</h1>
    
    <form action="insertPro.jsp"  method="post">
        도시이름: <input type ="text" name="cityName">
        경도: <input type="text" name="lng"><br>
        위도: <input type="text" name="lat"><br>
        <button type = "submit">저장</button>
    </form>
 
</body>
</html>
cs



② insertPro.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.PreparedStatement"%>
<%@page import="java.sql.Connection"%>
<%@page import="java.sql.Timestamp"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
     <%
         // post request 한글처리
         request.setCharacterEncoding("UTF-8");
     
         // 파라미터 정보 가져오기
         String cityName = request.getParameter("cityName");
         String strLng = request.getParameter("lng");
         String strLat = request.getParameter("lat");
         
         double lng = Double.parseDouble(strLng);
         double lat = Double.parseDouble(strLat);
         
         // 현재 시스템의 날짜 가져오기
         Timestamp reg_date = new Timestamp(System.currentTimeMillis()); //현재 시스템의 날짜 
         
         // INSERT를 위하 JDBC 변수 
         Connection con = null;
         PreparedStatement pstmt = null;
         
         // DB연결
        String url = "jdbc:oracle:thin:@localhost:1521:xe";
        String user = "scott";
        String passwd = "tiger";
        Class.forName("oracle.jdbc.OracleDriver");
        
        con = DriverManager.getConnection(url, user, passwd);
        String sql = "INSERT INTO location(city_name,longitude,latitude,reg_date) "
                    + " VALUES(?,?,?,?)";
        
        pstmt = con.prepareStatement(sql); // sql문 전달
        pstmt.setString(1,cityName);
        pstmt.setDouble(2, lng);
        pstmt.setDouble(3, lat);
        pstmt.setTimestamp(4, reg_date);
        
        // 데이터를 DB에 갱신
        pstmt.executeUpdate();
        %>
        <script>
        alert('저장완료');
        location.href='insertForm.jsp';
        </script>
        <% 
        pstmt.close();
        con.close();
        
         %>
 
</body>
</html>
cs



실행화면


>> 실행이후 DB의 TABLE  -> 추가된 행을 확인할 수 있다.