[쉽게 배우는 JSP 웹 프로그래밍] 16장 정리, 연습문제

JDBC의 개념과 사용법에 대해 다루고 있습니다. JDBC 드라이버 로딩 및 DBMS 접속 방법, 데이터베이스 쿼리 실행 방법, 쿼리문 실행 결과 값을 가져오는 방법 등을 학습하였습니다. 이를 통해 데이터베이스 연결, 쿼리 실행, 결과 처리 등의 과정을 이해하고, 실제 코드 예제를 통해 실습하였습니다.
DriedPollack's avatar
Mar 04, 2024
[쉽게 배우는 JSP 웹 프로그래밍] 16장 정리, 연습문제

JDBC 드라이버 로딩 및 DBMS 접속

connection.jsp

<%@ page contentType="text/html; charset=utf-8"%> <%@ page import="java.sql.*"%> <html> <head> <title>Database SQL</title> </head> <body> <% Connection conn = null; try { String url = "jdbc:mysql://localhost:3306/JSPBookDB"; String user = "root"; String password = "1234"; Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection(url, user, password); out.println("데이터베이스 연결이 성공했습니다."); } catch (SQLException ex) { out.println("데이터베이스 연결이 실패했습니다.<br>"); out.println("SQLException: " + ex.getMessage()); } finally { if(conn!=null) conn.close(); } %> </body> </html>
 

핵심 키워드

  • 데이터베이스에 접근하는 첫 단계는 JDBC 드라이버를 로딩하는 것이고, JDBC 드라이버를 로딩하고 나면 데이터베이스를 연결한다. 그리고 데이터베이스 관련 연결이 종료되면 데이터베이스 연결을 해제한다.
    • JDBC 드라이버 로딩 단계에서는 드라이버 인터페이스를 구현하는 작업으로 Class.forName() 메소드를 이용하여 JDBC 드라이버를 로딩한다.
    • JDBC 드라이버에서 데이터베이스와 연결된 커넥션을 가져오기 위해 DriverManager 클래스의 getConnection() 메소드를 사용한다.
    • 데이터베이스 연결이 더 이상 필요하지 ㅇ낳으면 close() 메소드로 생성한 Connection 객체를 해제한다.
 

JDBC 드라이버 로딩 및 DBMS 접속

member.sql

create table if not exists member( id varchar(20) not null, passwd varchar(20), name varchar(30), primary key(id) ); select * from member;

insert01.jsp

<%@ page contentType="text/html; charset=utf-8"%> <html> <head> <title>Database SQL</title> </head> <body> <form method="post" action="delete02_process.jsp"> <p>아이디 : <input type="text" name="id"> <p>비밀번호 : <input type="password" name="passwd"> <p>이름 : <input type="text" name="name"> <p><input type="submit" value="전송"> </form> </body> </html>

dbconn.jsp

<%@ page import="java.sql.*"%> <% Connection conn = null; String url = "jdbc:mysql://localhost:3306/JSPBookDB"; String user = "root"; String password = "1234"; Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection(url, user, password); %>

insert01_process.jsp

<%@ page contentType="text/html; charset=utf-8"%> <%@ page import="java.sql.*"%> <html> <head> <title>Database SQL</title> </head> <body> <%@ include file="dbconn.jsp"%> <% request.setCharacterEncoding("utf-8"); String id = request.getParameter("id"); String passwd = request.getParameter("passwd"); String name = request.getParameter("name"); Statement stmt = null; try { String sql = "INSERT INTO Member(id, passwd, name) VALUES('" + id + "','" + passwd + "','" + name + "')"; stmt = conn.createStatement(); stmt.executeUpdate(sql); out.println("Member 테이블 삽입이 성공했습니다."); } catch (SQLException ex) { out.println("Member 테이블 삽입이 실패했습니다.<br>"); out.println("SQLException: " + ex.getMessage()); } finally { if (stmt != null) stmt.close(); if (conn != null) conn.close(); } %> </body> </html>
 

핵심 키워드

  • Connection 객체를 생성하여 데이터베이스가 연결되었다면 쿼리 실행 객체를 이용하여 쿼리를 실행한다. 쿼리 실행 객체는 Statement, PreparedStatement, CallableStatement가 있다.
    • Statement 객체는 정적인 쿼리에 사용한다.
    • PreparedStatement 객체는 동적인 쿼리에 사용한다.
 

쿼리문 실행 결과 값 가져오기

select01.jsp

<%@ page contentType="text/html; charset=utf-8"%> <%@ page import="java.sql.*"%> <html> <head> <title>Database SQL</title> </head> <body> <%@ include file="dbconn.jsp"%> <table width="300" border="1"> <tr> <th>아이디</th> <th>비밀번호</th> <th>이름</th> </tr> <% ResultSet rs = null; Statement stmt = null; try { String sql = "select * from member"; stmt = conn.createStatement(); rs = stmt.executeQuery(sql); while (rs.next()) { String id = rs.getString("id"); String pw = rs.getString("passwd"); String name = rs.getString("name"); %> <tr> <td><%=id%></td> <td><%=pw%></td> <td><%=name%></td> </tr> <% } } catch (SQLException ex) { out.println("Member 테이블 호출이 실패했습니다.<br>"); out.println("SQLException: " + ex.getMessage()); } finally { if (rs != null) rs.close(); if (stmt != null) stmt.close(); if (conn != null) conn.close(); } %> </table> </body> </html>

select02.jsp

<%@ page contentType="text/html; charset=utf-8"%> <%@ page import="java.sql.*"%> <html> <head> <title>Database SQL</title> </head> <body> <%@ include file="dbconn.jsp"%> <table width="300" border="1"> <tr> <th>아이디</th> <th>비밀번호</th> <th>이름</th> </tr> <% ResultSet rs = null; PreparedStatement pstmt = null; try { String sql = "select * from member"; pstmt = conn.prepareStatement(sql); rs = pstmt.executeQuery(); while (rs.next()) { String id = rs.getString("id"); String pw = rs.getString("passwd"); String name = rs.getString("name"); %> <tr> <td><%=id%></td> <td><%=pw%></td> <td><%=name%></td> </tr> <% } } catch (SQLException ex) { out.println("Member 테이블 호출이 실패했습니다.<br>"); out.println("SQLException: " + ex.getMessage()); } finally { if (rs != null) rs.close(); if (pstmt != null) pstmt.close(); if (conn != null) conn.close(); } %> </table> </body> </html>

update02_process.jsp

<%@ page contentType="text/html; charset=utf-8"%> <%@ page import="java.sql.*"%> <html> <head> <title>Database SQL</title> </head> <body> <%@ include file="dbconn.jsp"%> <% request.setCharacterEncoding("utf-8"); String id = request.getParameter("id"); String passwd = request.getParameter("passwd"); String name = request.getParameter("name"); ResultSet rs = null; PreparedStatement pstmt = null; try { String sql = "select id, passwd from member where id=?"; pstmt = conn.prepareStatement(sql); pstmt.setString(1, id); rs = pstmt.executeQuery(); if (rs.next()) { String rId = rs.getString("id"); String rPasswd = rs.getString("passwd"); if (id.equals(rId) && passwd.equals(rPasswd)) { sql = "update member set name=? where id=?"; pstmt = conn.prepareStatement(sql); pstmt.setString(1, name); pstmt.setString(2, id); pstmt.executeUpdate(); out.println("Member 테이블을 수정했습니다."); } else out.println("일치하는 비밀번호가 아닙니다."); } else out.println("Member 테이블에 일치하는 아이디가 없습니다."); } catch (SQLException ex) { out.println("SQLException: " + ex.getMessage()); } finally { if (rs != null) rs.close(); if (pstmt != null) pstmt.close(); if (conn != null) conn.close(); } %> </body> </html>

delete02_process.jsp

<%@ page contentType="text/html; charset=utf-8"%> <%@ page import="java.sql.*"%> <html> <head> <title>Database SQL</title> </head> <body> <%@ include file="dbconn.jsp"%> <% request.setCharacterEncoding("utf-8"); String id = request.getParameter("id"); String passwd = request.getParameter("passwd"); String name = request.getParameter("name"); ResultSet rs = null; PreparedStatement pstmt = null; try { String sql = "select id, passwd from member where id=?"; pstmt = conn.prepareStatement(sql); pstmt.setString(1, id); rs = pstmt.executeQuery(); if (rs.next()) { String rId = rs.getString("id"); String rPasswd = rs.getString("passwd"); if (id.equals(rId) && passwd.equals(rPasswd)) { sql = "delete from member where id=? and passwd=?"; pstmt = conn.prepareStatement(sql); pstmt.setString(1, id); pstmt.setString(2, passwd); pstmt.executeUpdate(); out.println("Member 테이블을 삭제했습니다."); } else out.println("일치하는 비밀번호가 아닙니다."); } else out.println("Member 테이블에 일치하는 아이디가 없습니다."); } catch (SQLException ex) { out.println("SQLException: " + ex.getMessage()); } finally { if (rs != null) rs.close(); if (pstmt != null) pstmt.close(); if (conn != null) conn.close(); } %> </body> </html>
 

핵심 키워드

  • select 쿼리문 실행 시 excuteQuery() 메소드를 사용한 후, 실행 결과가 java.sql.ResultSet 형으로 변환된다. ResultSet 객체는 PreparedStatement 객체로 select 문을 사용하여 얻어온 레코드 값을 테이블 형태로 가지는 객체다.
 

연습문제

practice01.jsp

01 1. java.sql.* 패키지 임포트 2. JDBC 드라이버 로딩 3. 데이터베이스 접속을 위한 Connection 객체 생성 4. 쿼리문을 실행하기 위한 Statement/PreparedStatement/CallableStatement 객체 생성 5. 쿼리 실행 6. 쿼리 실행의 결과 값(int, ResultSet) 사용 7. 사용된 객체 (Statement/PreparedStatement/CallableStatement)종료 02 JDBC 드라이버 로딩 단계에서는 드라이버 인터페이스를 구현하는 작업으로 Class.forName() 메소드를 이용하여 JDBC 드라이버를 로딩한다. JDBC 드라이버가 로딩되면 자동으로 객체가 생성되고 DriverManager 클래스에 등록된다. JDBC 드라이버에서 데이터베이스와 연결된 커넥션을 가져오기 위해 DriverManager 클래스의 getConnection() 메소드를 사용한다. 데이터베이스 연결이 더 이상 필요하지 않으면 데이터베이스와 JDBC 리소스가 자동으로 닫힐 때까지 대기하는 것이 아니라 close() 메소드로 Connection 객체를 해제한다. 03 Statement 객체는 정적인 쿼리에 사용한다. PreparedStatement 객체는 동적인 쿼리에 사용한다.

practice04.jsp

<%@ page contentType="text/html; charset=utf-8"%> <html> <head> <title>Database SQL</title> </head> <body> <form method="post" action="practice04_process.jsp"> <p>학번 : <input type="text" name="num"> <p>학과 : <input type="text" name="depart"> <p>이름 : <input type="text" name="name"> <p>주소 : <input type="text" name="address"> <p>연락처 : <input type="text" name="phone"> <p><input type="submit" value="전송"> </form> </body> </html>

dbconn.jsp

<%@ page import="java.sql.*"%> <% Connection conn = null; String url = "jdbc:mysql://localhost:3306/JSPBookDB"; String user = "root"; String password = "1234"; Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection(url, user, password); %>

practice04_process.jsp

<%@ page contentType="text/html; charset=utf-8"%> <%@ page import="java.sql.*"%> <html> <head> <title>Database SQL</title> </head> <body> <%@ include file="dbconn.jsp"%> <% Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection(url, user, password); request.setCharacterEncoding("utf-8"); String num = request.getParameter("num"); String depart = request.getParameter("depart"); String name = request.getParameter("name"); String address = request.getParameter("address"); String phone = request.getParameter("phone"); PreparedStatement pstmt = null; try { String sql = "INSERT INTO student VALUES(?,?,?,?,?)"; pstmt = conn.prepareStatement(sql); pstmt.setString(1, num); pstmt.setString(2, depart); pstmt.setString(3, name); pstmt.setString(4, address); pstmt.setString(5, phone); pstmt.executeUpdate(); out.println("Student 테이블 삽입이 성공했습니다."); } catch (SQLException ex) { out.println("Student 테이블 삽입이 실패했습니다.<br>"); out.println("SQLException: " + ex.getMessage()); } finally { if (pstmt != null) pstmt.close(); if (conn != null) conn.close(); } %> </body> </html>

practice05.jsp

<%@ page contentType="text/html; charset=utf-8"%> <%@ page import="java.sql.*"%> <html> <head> <title>Database SQL</title> </head> <body> <%@ include file="dbconn.jsp"%> <table width="400" border="1"> <tr> <th>학번</th> <th>학과</th> <th>이름</th> <th>주소</th> <th>연락처</th> </tr> <% ResultSet rs = null; PreparedStatement pstmt = null; try { String sql = "select * from student"; pstmt = conn.prepareStatement(sql); rs = pstmt.executeQuery(); while (rs.next()) { String num = rs.getString("num"); String depart = rs.getString("depart"); String name = rs.getString("name"); String address = rs.getString("address"); String phone = rs.getString("phone"); %> <tr> <td><%=num%></td> <td><%=depart%></td> <td><%=name%></td> <td><%=address%></td> <td><%=phone%></td> </tr> <% } } catch (SQLException ex) { out.println("Student 테이블 호출이 실패했습니다.<br>"); out.println("SQLException: " + ex.getMessage()); } finally { if (rs != null) rs.close(); if (pstmt != null) pstmt.close(); if (conn != null) conn.close(); } %> </table> </body> </html>
 

핵심 키워드

  • select 쿼리문 실행 시 excuteQuery() 메소드를 사용한 후, 실행 결과가 java.sql.ResultSet 형으로 변환된다. ResultSet 객체는 PreparedStatement 객체로 select 문을 사용하여 얻어온 레코드 값을 테이블 형태로 가지는 객체다.
 

결론

해당 코드를 작성하면서 JDBC의 개념, JDBC 드라이버 로딩 및 DBMS 접속 방법, 데이터베이스 쿼리 실행 방법, 쿼리문 실행 결과 값을 가져오는 방법을 익힐 수 있었다.
Share article

More articles

See more posts
RSSPowered by inblog