데이터베이스 프로그래밍 기초(4) : JSP에서 JDBC 프로그래밍하기(2)

de_sj_awa·2021년 5월 21일
0

6. 데이터베이스 커넥션

JDBC를 이용해서 데이터베이스를 사용하려면 데이터베이스와 연결된 커넥션을 구해야 한다. java.sql.Connection 타입이 데이터베이스 커넥션을 나타내며, java.sql.DriverManager 클래스가 제공하는 getConnection() 메서드를 사용해서 커넥션을 구할 수 있다. DriverManager 클래스는 다음의 두 getConnection() 메서드를 제공하고 있다.

  • DriverManager.getConnection(String jdbcURL)
  • DriverManager.getConnection(String jdbcURL, String user, String password)

getConnection() 메서드의 jdbcURL은 데이터베이스에 연결할 때 사용할 JDBC URL을 나타낸다. user와 password는 데이터베이스의 계정과 암호를 나타낸다.

DriverManager.getConnection() 메서드는 Connection 객체를 생성하지 못하면 SQLException을 발생시킨다. 따라서, getConnection() 메서드를 사용할 때에는 try-catch 블록을 사용해서 SQLException에 대한 익셉션을 처리해야 한다.

Connection 객체를 다 사용한 뒤에는 close() 메서들 호출해서 Connection 객체가 사용한 시스템 자원을 반환해야 한다. 그렇지 않으면 시스템 자원이 불필요하게 소모되어 커넥션을 구할 수 없는 상황이 발생할 수 있다.

Connection conn = null;

try{
        String jdbcDriver = "jdbc:mysql://localhost:3306/jsptest?"+"useUnicode=true&characterEncoding=utf8";
        String dbUser="";
        String dbPass="";

        String query = "select * from MEMBER order by MEMBERID";

        // 2. 데이터베이스 커넥션 생성
        conn = DriverManager.getConnection(jdbcDriver, dbUser, dbPass);
        ...
         }catch (SQLException ex){
        out.println(ex.getMessage());
        ex.printStackTrace();
}finally {
    // 7. 커넥션 종료
    if(conn != null) try { conn.close(); } catch (SQLException ex) {}
}

위 코드를 보면 finally 블록에서 Connection 객체의 close() 메서드를 호출해서 사용한 자원을 반환하고 있다. DriverManager.getConnection() 메서드가 익셉션을 발생시킬 경우 conn에 Connection 객체가 할당되지 않으므로, null인지의 여부를 판단한 후에 close() 메서드를 호출해야 한다.

7. Statmenet를 사용한 쿼리 실행

Connection 객체를 생성한 후에는 Connection 객체로부터 Statment를 생성하고 쿼리를 실행할 수 있다. Statement는 다음과 같이 Connection의 createStatement() 메서드를 사용하여 생성한다.

Statement stmt = conn.createStatement();

Statement 객체를 사용하면 쿼리를 실행할 수 있다. 쿼리를 실행할 때 사용하는 메서드는 다음과 같다.

  • ResultSet executeQuery(String query) : SELECT 쿼리를 실행한다.
  • int executeUpdate(String quert) : INSERT, UPDATE, DELETE 쿼리를 실행한다.

executeQuery() 메서드는 SELECT 쿼리의 결과값을 java.sql.ResultSet 객체에 저장해서 리턴한다. 두 번째 executeUpdate() 메서드는 INSERT, UPDATE, DELETE 쿼리를 실행하고, 그 결과로 변경된 (또는 삽입된) 레코드의 개수를 리턴한다. 이 절에서는 Statement를 사용해서 값을 변경하는 예제를 작성할 것이다. 작성할 예제는 아이디와 새로운 이름을 입력하면 MEMBER 테이블의 NAME 칼럼 값을 변경하는 코드이다.

먼저 아이디와 새로운 이름을 입력받는 폼을 출력해주는 JSP를 아래 예제코드와 같이 작성한다.

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>이름 변경폼</title>
</head>
<body>

<form action="/chap14/update/update.jsp" method="post">
  <table border="1">
    <tr>
      <td>아이디</td>
      <td><input type="text" name="memberID" size="10"></td>
      <td>이름</td>
      <td><input type="text" name="name" size="10"></td>
    </tr>
    <tr>
      <td colspan="4"><input type="submit" value="변경"></td>
    </tr>
  </table>
</form>

</body>
</html>

실행 결과는 다음과 같다.

위의 폼을 처리해주는 update.jsp는 파라미터로부터 회원 아이디와 이름을 입력 받아 MEMBER 테이블의 NAME 칼럼 값을 변경한다. update.jsp의 코드는 아래와 같다.

<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<%@ page import="java.sql.DriverManager" %>
<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.Statement" %>
<%@ page import="java.sql.SQLException" %>

<%
  request.setCharacterEncoding("utf-8");

  String memberID = request.getParameter("memberID");
  String name = request.getParameter("name");

  int updateCount = 0;

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

  Connection conn = null;
  Statement stmt = null;

  try{
    String jdbcDriver = "jdbc:mysql://localhost:3306/jsptest?"+"useUnicode=true&characterEncoding=utf8";
    String dbUser="jspexam";
    String dbPass="jsppw";

    String query = "update MEMBER set NAME = '" + name + "'" + "where MEMBERID = '" + memberID + "'";

    conn = DriverManager.getConnection(jdbcDriver, dbUser, dbPass);
    stmt = conn.createStatement();
    updateCount = stmt.executeUpdate(query);
  }finally {
    if(stmt != null) try {stmt.close();} catch(SQLException ex){}
    if(conn != null) try {conn.close();} catch(SQLException ex){}
  }
%>
<html>
<head>
    <title>이름 변경</title>
</head>
<body>
<%
  if(updateCount > 0){ %>
<%=memberID%>의 이름을 <%=name%>()로 변경
<% } %>
</body>
</html>

존재하는 아이디를 입력했다면 실행 결과는 다음과 같다.

실제로 값이 변경되었는지를 확인해보기 위해서 MEMBER 테이블의 레코드 목록을 출력해주는 viewMemberList.jsp를 실행해보자. 그러면 아래와 같이 입력한 값으로 NAME 칼럼이 변경된 것을 확인할 수 있을 것이다.

Statement의 executeUpdate() 메서드는 변경된 레코드의 개수를 리턴한다고 했다. update.jsp의 경우 UPDATE 쿼리를 통해서 변경된 레코드의 개수를 리턴한다. update.jsp에서 사용하는 UPDATE 쿼리는 다음과 같은 형태이다.

update MEMBER set NAME = '이름' where MEMBERID = '아이디';

따라서, WHERE 조건에서 지정한 아이디가 존재하지 않으면 변경된 레코드가 존재하지 않으므로 Statement.executeUpdate() 메서드는 0을 리턴한다. udpate.jsp는 변경된 레코드의 개수를 사용해서 지정한 아이디가 존재하는지 여부를 판단하고 있다.

참고

  • 최범균의 JSP2.3 웹 프로그래밍
profile
이것저것 관심많은 개발자.

0개의 댓글