解答例 - 実習課題1 - 6.DataSourceからConnectionを取得する
(実習課題1)
サンプルのサーブレットを実行させなさい。また「product」テーブルにデータを追加する機能を、Webアプリケーションに追加しなさい。
解答例
/** * DataSourceInsertServlet.java * TECHSCORE JDBC6章 実習課題1 * * Copyright (c) 2004 Four-Dimensional Data, Inc. */ package com.techscore.jdbc.chapter6.exercise1; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.ServletException; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.sql.DataSource; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.io.PrintWriter; import java.io.IOException; public class DataSourceInsertServlet extends HttpServlet { private DataSource dataSource = null; public void init() throws ServletException { try { Context context = new InitialContext(); dataSource = (DataSource) context.lookup("java:comp/env/jdbc/datasource"); } catch (NamingException e) { throw new ServletException(e); } } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html; charset=SJIS"); PrintWriter writer = response.getWriter(); writer.println("<html><body>"); Connection conn = null; try { conn = dataSource.getConnection(); PreparedStatement statement = conn.prepareStatement("insert into product values(101,'Viz','compact car',100)"); int result = statement.executeUpdate(); writer.println(result + "行データを追加"); } catch (SQLException e) { e.printStackTrace(writer); } finally { try { if (conn != null) conn.close(); } catch (SQLException e) {} } writer.println("</body></html>"); } }