教育サーバーのページ
オンラインテキスト目次
システムプログラミング演習

データベース との連携 (JSP)

データベースの検索

次のプログラム JdbcCustomerTable.jsp は、 ブラウザのリクエスト(HTTPのGETリクエスト)対して、 指定したWebサーバ下のディレクトリ(アプリケーションの ルートディレクトリ)下に格納されているJSPファイルを 実行することで、ブラウザ上にデータベースの検索結果を テキスト表示するプログラムである。

<%@page contentType="text/html; charset=Shift_JIS" pageEncoding="Shift_JIS"%>
<%@page import="java.sql.*"%>
<%!
// サーブレットのinitメソッドに相当
public void jspInit() {
    try {
        // JDBCドライバをロード
        Class.forName("com.pointbase.jdbc.jdbcUniversalDriver");
    } catch (Exception e) {
        e.printStackTrace();
    }
}
%>

<html>
<head><title>CUSTOMER_TBLテーブルの内容(JSP版)</title></head>

<body>
<P>JSPによるデータベースのアクセス</P>
<table border='1'><tr><th>顧客番号</th><th>名前</th><th>電話番号</th></tr>

<%
        // データベースへのアクセス開始
        Connection con = null;
        Statement stmt = null;
        ResultSet rs = null;
        try {
            // データベースに接続するConnectionオブジェクトの取得
            con = DriverManager.getConnection(
                "jdbc:pointbase:server://localhost/sample",
                "PBPUBLIC", "PBPUBLIC");
            // データベース操作を行うためのStatementオブジェクトの取得
            stmt = con.createStatement();
            // SQL()を実行して、結果を得る
            rs = stmt.executeQuery(
              "SELECT CUSTOMER_NUM, NAME, PHONE FROM CUSTOMER_TBL");

            // 得られた結果をレコードごとに表示
            while (rs.next()) {
%>
                <tr>
                <%-- レコードのCUSTOMER_NUMフィールドを表示 --%>
                <td><%= rs.getString("CUSTOMER_NUM")%></td>
                <%-- レコードのNAMEフィールドを表示 --%>
                <td><%= rs.getString("NAME")%></td>
                <%-- レコードのPHONEフィールドを表示 --%>
                <td><%= rs.getString("PHONE")%></td>
                </tr>
<%
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // データベースとの接続をクローズ
            try { rs.close(); } catch (Exception e) {}
            try { stmt.close(); } catch (Exception e) {}
            try { con.close(); } catch (Exception e) {}
        }
%>

        </table>
</body>
</html>

たとえば、Webサーバが動いているホストlocalhostの Webアプリケーションのルートディレクトリ下に格納されている JSPファイルJdbcCustomerTable.jspを実行する。 そうすると、指定されたデータベースに接続され、SQL文により 検索がおこなわれ、その結果がブラウザ上に表示される。

プログラム JdbcCustomerTable.jsp の説明

<%@page contentType="text/html; charset=Shift_JIS" pageEncoding="Shift_JIS"%>
は、pageディレクティブ(<%@page 〜%>)であり、JSPファイルを実行するJSP コンテナに対する指示を表す。この指示は、JSPからServletを自動的に変換・実行する ために用いられる。このpageディレクティブでは、JSPが出力するデータ形式 (contentType="text/html")、そこで使う文字コード(charset="Shift_JIS")と、 ソースコードの文字コード(pageEncoding="Shift_JIS")をそれぞれ指定している。

<%@page import="java.sql.*"%>
も、pageディレクティブ(<%@page 〜%>)であり、JDBC APIを 構成するクラスライブラリ(パッケージ)を使えるように宣言している。

<%! 〜 %>により、以下のようなjspInitメソッドが定義される。 jspInitメソッドは、SunONEに組み込まれたデータベース管理システム PointBaseのJDBCドライバのロードをおこなう。JDBCドライバは、 PointBase用のcom.pointbase.jdbc.jdbcUniversalDriverを用いる。

<%!
// サーブレットのinitメソッドに相当
public void jspInit() {
    try {
        // JDBCドライバをロード
        Class.forName("com.pointbase.jdbc.jdbcUniversalDriver");
    } catch (Exception e) {
        e.printStackTrace();
    }
}
%>

以下は、SQLによる検索結果を取り出して、HTML形式で出力・表示する部分 である。

<html>
<head><title>CUSTOMER_TBLテーブルの内容(JSP版)</title></head>

<body>
<P>JSPによるデータベースのアクセス</P>
<table border='1'><tr><th>顧客番号</th><th>名前</th><th>電話番号</th></tr>

<%
        // データベースへのアクセス開始
        Connection con = null;
        Statement stmt = null;
        ResultSet rs = null;
        try {
            // データベースに接続するConnectionオブジェクトの取得
            con = DriverManager.getConnection(
                "jdbc:pointbase:server://localhost/sample",
                "PBPUBLIC", "PBPUBLIC");
            // データベース操作を行うためのStatementオブジェクトの取得
            stmt = con.createStatement();
            // SQL()を実行して、結果を得る
            rs = stmt.executeQuery(
              "SELECT CUSTOMER_NUM, NAME, PHONE FROM CUSTOMER_TBL");

            // 得られた結果をレコードごとに表示
            while (rs.next()) {
%>
                <tr>
                <%-- レコードのCUSTOMER_NUMフィールドを表示 --%>
                <td><%= rs.getString("CUSTOMER_NUM")%></td>
                <%-- レコードのNAMEフィールドを表示 --%>
                <td><%= rs.getString("NAME")%></td>
                <%-- レコードのPHONEフィールドを表示 --%>
                <td><%= rs.getString("PHONE")%></td>
                </tr>
<%
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // データベースとの接続をクローズ
            try { rs.close(); } catch (Exception e) {}
            try { stmt.close(); } catch (Exception e) {}
            try { con.close(); } catch (Exception e) {}
        }
%>

        </table>
</body>
</html>

まず、JSPからの出力されるデータ(ここでは、 HTML文書)の形式を指定している。データの更新結果は、 JdbcCustomerTable.jspを呼び出すことで表示される。

<html>
<head><title>CUSTOMER_TBLテーブルの内容(JSP版)</title></head>

<body>
<P>JSPによるデータベースのアクセス</P>
<table border='1'><tr><th>顧客番号</th><th>名前</th><th>電話番号</th></tr>

次に、スクリプトレットにより、本プログラムの主処理が以下のようにおこなわれる。

<%
        // データベースへのアクセス開始
        Connection con = null;
        Statement stmt = null;
        ResultSet rs = null;
        try {
            // データベースに接続するConnectionオブジェクトの取得
            con = DriverManager.getConnection(
                "jdbc:pointbase:server://localhost/sample",
                "PBPUBLIC", "PBPUBLIC");
            // データベース操作を行うためのStatementオブジェクトの取得
            stmt = con.createStatement();
            // SQL()を実行して、結果を得る
            rs = stmt.executeQuery(
              "SELECT CUSTOMER_NUM, NAME, PHONE FROM CUSTOMER_TBL");

            // 得られた結果をレコードごとに表示
            while (rs.next()) {
%>
                <tr>
                <%-- レコードのCUSTOMER_NUMフィールドを表示 --%>
                <td><%= rs.getString("CUSTOMER_NUM")%></td>
                <%-- レコードのNAMEフィールドを表示 --%>
                <td><%= rs.getString("NAME")%></td>
                <%-- レコードのPHONEフィールドを表示 --%>
                <td><%= rs.getString("PHONE")%></td>
                </tr>
<%
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // データベースとの接続をクローズ
            try { rs.close(); } catch (Exception e) {}
            try { stmt.close(); } catch (Exception e) {}
            try { con.close(); } catch (Exception e) {}
        }
%>

まず、必要な変数の初期化をおこなう。

      Connection con = null;
      Statement stmt = null;
      ResultSet rs = null;

try節の中では、データベースに接続するConnectionオブジェクトの取得 をおこなう。ここでは、接続するデータベースのURLを"jdbc:pointbase:server://localhost/sample"、ユーザ名が"PBPUBLIC"を、パスワードを "PBPUBLIC"としている。

       con = DriverManager.getConnection(
           "jdbc:pointbase:server://localhost/sample",
           "PBPUBLIC", "PBPUBLIC");
それから、データベース操作を行うためのStatementオブジェクトの取得 をおこなう。

       stmt = con.createStatement();

さらに、SQL文を実行して、結果を得るために、以下のような 処理をおこなう。

       rs = stmt.executeQuery(
         "SELECT CUSTOMER_NUM, NAME, PHONE FROM CUSTOMER_TBL");

そして、得られた結果をレコードごとに表示するために、 以下の処理を実行する。具体的には、レコードのCUSTOMER_NUM フィールド、NAMEフィールド、PHONEフィールドを順番に表示する。 ここでは、検索結果が格納されたResultSetオブジェクトから、 指定されたフィールド名に対応する値が表示される。

            // 得られた結果をレコードごとに表示
            while (rs.next()) {
%>
                <tr>
                <%-- レコードのCUSTOMER_NUMフィールドを表示 --%>
                <td><%= rs.getString("CUSTOMER_NUM")%></td>
                <%-- レコードのNAMEフィールドを表示 --%>
                <td><%= rs.getString("NAME")%></td>
                <%-- レコードのPHONEフィールドを表示 --%>
                <td><%= rs.getString("PHONE")%></td>
                </tr>
<%
            }

データベース処理の後処理をあらわす。finally節では、最終的に おこなわれるデータベースとの接続がクローズされることが記述 されている。

<%
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // データベースとの接続をクローズ
            try { rs.close(); } catch (Exception e) {}
            try { stmt.close(); } catch (Exception e) {}
            try { con.close(); } catch (Exception e) {}
        }
%>

ブラウザに出力されるHTML文章のtableタグ、bodyタグ、 htmlタグのそれぞれの終了タグを指定している。

        </table>
</body>
</html>

データの更新

以下のJdbcUpdate.htmlでは、Formタグのaction属性の値には、 送信ボタンが押された時に、テキスト入力フィールドに入力された文字列を JSPプログラムであるJdbcUpdate.jspに渡すことを指定している。

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<HTML>
  <HEAD>
    <TITLE>データベースの変更</TITLE>
  </HEAD>
  <BODY>
  <FORM method=POST action='JdbcUpdate.jsp'>
    <TABLE border='1'>
      <TR><TH>CUSTOMER_NUM</TH><TD><INPUT type=text name='customer_num'></TD></TR>
      <TR><TH>DISCOUNT_CODE</TH><TD><INPUT type=text name='discount_code'></TD></TR>
      <TR><TH>ZIP</TH><TD><INPUT type=text name='zip'></TD></TR>
      <TR><TH>NAME</TH><TD><INPUT type=text name='name'></TD></TR>
      <TR><TH>PHONE</TH><TD><INPUT type=text name='phone'></TD></TR>
      <TR><TD><INPUT type=submit value='送信'></TD></TR>
    </TABLE>
  </FORM>
  </BODY>
</HTML>

次のプログラム JdbcUpdate.jsp は、指定したWebサーバ下の ルートディレクトリ下に格納されているJSPファイルを実行することで、 ブラウザ上にデータベースの更新結果をテキスト表示するプログラム である。

<%@page contentType="text/html; charset=Shift_JIS" pageEncoding="Shift_JIS"%>
<%@page import="java.sql.*"%>
<%!
// サーブレットのinitメソッドに相当
public void jspInit() {
    try {
        // JDBCドライバをロード
        Class.forName("com.pointbase.jdbc.jdbcUniversalDriver");
    } catch (Exception e) {
        e.printStackTrace();
    }
}
%>

<html>
<head><title>CUSTOMER_TBLテーブルのUpdate(JSP版)</title></head>

<body>
<P>JSPによるデータベースのUpdate</P>


<%
        Connection con = null;
        Statement stmt = null;
        try {
            con = DriverManager.getConnection(
                "jdbc:pointbase:server://localhost/sample",
                "PBPUBLIC", "PBPUBLIC");

            stmt = con.createStatement();

            String customer_num = request.getParameter("customer_num");
            String discount_code = request.getParameter("discount_code");
            String zip = request.getParameter("zip");
            String name = new String(
                            request.getParameter("name").getBytes("8859_1"),
                            "JISAutoDetect");
            String phone = request.getParameter("phone");

            StringBuffer buf = new StringBuffer();
            buf.append("UPDATE CUSTOMER_TBL SET ");
            buf.append("DISCOUNT_CODE = '");
            buf.append(discount_code);
            buf.append("', ZIP = '");
            buf.append(zip);
            buf.append("', NAME = '");
            buf.append(name);
            buf.append("', PHONE = '");
            buf.append(phone);
            buf.append("' WHERE CUSTOMER_NUM = ");
            buf.append(customer_num);
            stmt.executeUpdate(buf.toString());
            
            try { stmt.close(); } catch (Exception e) {}
            try { con.close(); } catch (Exception e) {}

        } catch (Exception e) {
            e.printStackTrace();
        }

%>
<jsp:forward page="JdbcCustomerTable.jsp" />
</body>
</html>

たとえば、Webサーバが動いているホストlocalhostのWebアプリケーションの ルートディレクトリ下に格納されているJSPファイルJdbcUpdate.jspを 実行する。そうすると、指定されたデータベースに接続され、SQL文により データの変更がおこなわれ、その結果がブラウザ上に表示される。

プログラム JdbcUpdate.jsp の説明

<%@page contentType="text/html; charset=Shift_JIS" pageEncoding="Shift_JIS"%>
は、pageディレクティブ(<%@page 〜%>)であり、JSPファイルを実行するJSP コンテナに対する指示を表す。この指示は、JSPからServletを自動的に変換・実行する ために用いられる。このpageディレクティブでは、JSPが出力するデータ形式 (contentType="text/html")、そこで使う文字コード(charset="Shift_JIS")と、 ソースコードの文字コード(pageEncoding="Shift_JIS")をそれぞれ指定している。

<%@page import="java.sql.*"%>
も、pageディレクティブ(<%@page 〜%>)であり、JDBC APIを 構成するクラスライブラリ(パッケージ)を使えるように宣言している。

<%! 〜 %>により、以下のようなjspInitメソッドが定義される。 jspInitメソッドは、SunONEに組み込まれたデータベース管理システム PointBaseのJDBCドライバのロードをおこなう。JDBCドライバは、 PointBase用のcom.pointbase.jdbc.jdbcUniversalDriverを用いる。

<%!
// サーブレットのinitメソッドに相当
public void jspInit() {
    try {
        // JDBCドライバをロード
        Class.forName("com.pointbase.jdbc.jdbcUniversalDriver");
    } catch (Exception e) {
        e.printStackTrace();
    }
}
%>

以下は、SQLによるデータベースの追加結果を、HTML形式で 出力・表示する部分である。

<html>
<head><title>CUSTOMER_TBLテーブルのUpdate(JSP版)</title></head>

<body>
<P>JSPによるデータベースのUpdate</P>


<%
        Connection con = null;
        Statement stmt = null;
        try {
            con = DriverManager.getConnection(
                "jdbc:pointbase:server://localhost/sample",
                "PBPUBLIC", "PBPUBLIC");

            stmt = con.createStatement();

            String customer_num = request.getParameter("customer_num");
            String discount_code = request.getParameter("discount_code");
            String zip = request.getParameter("zip");
            String name = new String(
                            request.getParameter("name").getBytes("8859_1"),
                            "JISAutoDetect");
            String phone = request.getParameter("phone");

            StringBuffer buf = new StringBuffer();
            buf.append("UPDATE CUSTOMER_TBL SET ");
            buf.append("DISCOUNT_CODE = '");
            buf.append(discount_code);
            buf.append("', ZIP = '");
            buf.append(zip);
            buf.append("', NAME = '");
            buf.append(name);
            buf.append("', PHONE = '");
            buf.append(phone);
            buf.append("' WHERE CUSTOMER_NUM = ");
            buf.append(customer_num);
            stmt.executeUpdate(buf.toString());
            
            try { stmt.close(); } catch (Exception e) {}
            try { con.close(); } catch (Exception e) {}

        } catch (Exception e) {
            e.printStackTrace();
        }
%>
<P> データベースの更新終了:</P>
<jsp:forward page="JdbcCustomerTable.jsp" />
</body>
</html>

次に、スクリプトレットにより、本プログラムの主処理が以下のようにおこなわれる。

<%
        Connection con = null;
        Statement stmt = null;
        try {
            con = DriverManager.getConnection(
                "jdbc:pointbase:server://localhost/sample",
                "PBPUBLIC", "PBPUBLIC");

            stmt = con.createStatement();

            String customer_num = request.getParameter("customer_num");
            String discount_code = request.getParameter("discount_code");
            String zip = request.getParameter("zip");
            String name = new String(
                            request.getParameter("name").getBytes("8859_1"),
                            "JISAutoDetect");
            String phone = request.getParameter("phone");

            StringBuffer buf = new StringBuffer();
            buf.append("UPDATE CUSTOMER_TBL SET ");
            buf.append("DISCOUNT_CODE = '");
            buf.append(discount_code);
            buf.append("', ZIP = '");
            buf.append(zip);
            buf.append("', NAME = '");
            buf.append(name);
            buf.append("', PHONE = '");
            buf.append(phone);
            buf.append("' WHERE CUSTOMER_NUM = ");
            buf.append(customer_num);
            stmt.executeUpdate(buf.toString());
            
            try { stmt.close(); } catch (Exception e) {}
            try { con.close(); } catch (Exception e) {}

        } catch (Exception e) {
            e.printStackTrace();
        }
%>

まず、必要な変数の初期化をおこなう。

      Connection con = null;
      Statement stmt = null;

次に、try節の中では、データベースに接続するConnectionオブジェクト の取得をおこなう。ここでは、接続するデータベースのURLを "jdbc:pointbase:server://localhost/sample"、ユーザ名が"PBPUBLIC"を、 パスワードを"PBPUBLIC"とする。

       con = DriverManager.getConnection(
           "jdbc:pointbase:server://localhost/sample",
           "PBPUBLIC", "PBPUBLIC");
それから、データベース操作を行うためのStatementオブジェクトの取得 をおこなう。

       stmt = con.createStatement();

さらに、データベース操作に必要な値をrequestオブジェクトから 取得する。

      String customer_num = request.getParameter("customer_num");
      String discount_code = request.getParameter("discount_code");
      String zip = request.getParameter("zip");
      String name = new String(
                      request.getParameter("name").getBytes("8859_1"),
                      "JISAutoDetect");
      String phone = request.getParameter("phone");

そして、更新操作を実行するためのSQL文を作成する。

         StringBuffer buf = new StringBuffer();
         buf.append("UPDATE CUSTOMER_TBL SET ");
         buf.append("DISCOUNT_CODE = '");
         buf.append(discount_code);
         buf.append("', ZIP = '");
         buf.append(zip);
         buf.append("', NAME = '");
         buf.append(name);
         buf.append("', PHONE = '");
         buf.append(phone);
         buf.append("' WHERE CUSTOMER_NUM = ");
         buf.append(customer_num);

上記で作成されたSQL文を実行するために、以下の処理をおこなう。

      stmt.executeUpdate(buf.toString());

以下では、データベースの後処理をおこなう。 finally節では、最終的におこなわれるデータベースとの接続が クローズが記述されている。

      try { stmt.close(); } catch (Exception e) {}
      try { con.close(); } catch (Exception e) {}
    } catch (Exception e) {
         e.printStackTrace();
    }
%>

そして、forwardアクションを用いて、データベースを検索する JSPプログラムJdbcCustomerTable.jspを呼び出す。

   <jsp:forward page="JdbcCustomerTable.jsp" />

ブラウザに出力されるHTML文章のtableタグ、bodyタグ、 htmlタグのそれぞれの終了タグを指定している。

        </table>
</body>
</html>

データの追加

以下のJdbcInsert.htmlでは、Formタグのaction属性の値には、 送信ボタンが押された時に、テキスト入力フィールドに入力された文字列を JSPプログラムであるJdbcInsert.jspに渡すことを指定している。

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<HTML>
  <HEAD>
    <TITLE>データベースへの追加</TITLE>
  </HEAD>
  <BODY>
  <FORM method=POST action='JdbcInsert.jsp'>
    <TABLE border='1'>
      <TR><TH>CUSTOMER_NUM</TH><TD><INPUT type=text name='customer_num'></TD></TR>
      <TR><TH>DISCOUNT_CODE</TH><TD><INPUT type=text name='discount_code'></TD></TR>
      <TR><TH>ZIP</TH><TD><INPUT type=text name='zip'></TD></TR>
      <TR><TH>NAME</TH><TD><INPUT type=text name='name'></TD></TR>
      <TR><TH>PHONE</TH><TD><INPUT type=text name='phone'></TD></TR>
      <TR><TD><INPUT type=submit value='送信'></TD></TR>
    </TABLE>
  </FORM>
  </BODY>
</HTML>

次のプログラム JdbcInsert.jsp は、指定したWebサーバ下の ルートディレクトリ下に格納されているJSPファイルを実行することで、 データベースへデータを追加した結果をブラウザ上にテキスト表示する プログラムである。

<%@page contentType="text/html; charset=Shift_JIS" pageEncoding="Shift_JIS"%>
<%@page import="java.sql.*"%>
<%!
// サーブレットのinitメソッドに相当
public void jspInit() {
    try {
        // JDBCドライバをロード
        Class.forName("com.pointbase.jdbc.jdbcUniversalDriver");
    } catch (Exception e) {
        e.printStackTrace();
    }
}
%>

<html>
<head><title>CUSTOMER_TBLテーブルのInsert(JSP版)</title></head>

<body>
<P>JSPによるデータベースのInsert</P>

<%
        Connection con = null;
        Statement stmt = null;
        try {
            con = DriverManager.getConnection(
                "jdbc:pointbase:server://localhost/sample",
                "PBPUBLIC", "PBPUBLIC");

            stmt = con.createStatement();

            String customer_num = request.getParameter("customer_num");
            String discount_code = request.getParameter("discount_code");
            String zip = request.getParameter("zip");
            String name = new String(
                            request.getParameter("name").getBytes("8859_1"),
                            "JISAutoDetect");
            String phone = request.getParameter("phone");

            StringBuffer buf = new StringBuffer();
            buf.append("INSERT INTO CUSTOMER_TBL (");
            buf.append("CUSTOMER_NUM, DISCOUNT_CODE, ZIP, NAME, PHONE) ");
            buf.append("VALUES (");
            buf.append(customer_num);
            buf.append(",'");
            buf.append(discount_code);
            buf.append("','");
            buf.append(zip);
            buf.append("','");
            buf.append(name);
            buf.append("','");
            buf.append(phone);
            buf.append("')");
            stmt.executeUpdate(buf.toString());

            try { stmt.close(); } catch (Exception e) {}
            try { con.close(); } catch (Exception e) {}

        } catch (Exception e) {
            e.printStackTrace();
        }
%>

<jsp:forward page="JdbcCustomerTable.jsp" />

</body>
</html>

たとえば、Webサーバが動いているホストlocalhostのWebアプリケーションの ルートディレクトリ下に格納されているJSPファイルJdbcInsert.jspを 実行する。そうすると、指定されたデータベースに接続され、SQL文により データの追加がおこなわれ、その結果がブラウザ上に表示される。

プログラム JdbcInsert.jsp の説明

<%@page contentType="text/html; charset=Shift_JIS" pageEncoding="Shift_JIS"%>
は、pageディレクティブ(<%@page 〜%>)であり、JSPファイルを実行するJSP コンテナに対する指示を表す。この指示は、JSPからServletを自動的に変換・実行する ために用いられる。このpageディレクティブでは、JSPが出力するデータ形式 (contentType="text/html")、そこで使う文字コード(charset="Shift_JIS")と、 ソースコードの文字コード(pageEncoding="Shift_JIS")をそれぞれ指定している。

<%@page import="java.sql.*"%>
も、pageディレクティブ(<%@page 〜%>)であり、JDBC APIを 構成するクラスライブラリ(パッケージ)を使えるように宣言している。

<%! 〜 %>により、以下のようなjspInitメソッドが定義される。 jspInitメソッドは、SunONEに組み込まれたデータベース管理システム PointBaseのJDBCドライバのロードをおこなう。JDBCドライバは、 PointBase用のcom.pointbase.jdbc.jdbcUniversalDriverを用いる。

<%!
// サーブレットのinitメソッドに相当
public void jspInit() {
    try {
        // JDBCドライバをロード
        Class.forName("com.pointbase.jdbc.jdbcUniversalDriver");
    } catch (Exception e) {
        e.printStackTrace();
    }
}
%>

以下は、SQLによるデータベースへの追加結果を、HTML形式で 出力・表示する部分である。

<html>
<head><title>CUSTOMER_TBLテーブルのInsert(JSP版)</title></head>

<body>
<P>JSPによるデータベースのInsert</P>

<%
        Connection con = null;
        Statement stmt = null;
        try {
            con = DriverManager.getConnection(
                "jdbc:pointbase:server://localhost/sample",
                "PBPUBLIC", "PBPUBLIC");

            stmt = con.createStatement();

            String customer_num = request.getParameter("customer_num");
            String discount_code = request.getParameter("discount_code");
            String zip = request.getParameter("zip");
            String name = new String(
                            request.getParameter("name").getBytes("8859_1"),
                            "JISAutoDetect");
            String phone = request.getParameter("phone");

            StringBuffer buf = new StringBuffer();
            buf.append("INSERT INTO CUSTOMER_TBL (");
            buf.append("CUSTOMER_NUM, DISCOUNT_CODE, ZIP, NAME, PHONE) ");
            buf.append("VALUES (");
            buf.append(customer_num);
            buf.append(",'");
            buf.append(discount_code);
            buf.append("','");
            buf.append(zip);
            buf.append("','");
            buf.append(name);
            buf.append("','");
            buf.append(phone);
            buf.append("')");
            stmt.executeUpdate(buf.toString());

            try { stmt.close(); } catch (Exception e) {}
            try { con.close(); } catch (Exception e) {}

        } catch (Exception e) {
            e.printStackTrace();
        }
%>

<jsp:forward page="JdbcCustomerTable.jsp" />

</body>
</html>

次に、スクリプトレットにより、本プログラムの主処理が以下のようにおこなわれる。

<%
        Connection con = null;
        Statement stmt = null;
        try {
            con = DriverManager.getConnection(
                "jdbc:pointbase:server://localhost/sample",
                "PBPUBLIC", "PBPUBLIC");

            stmt = con.createStatement();

            String customer_num = request.getParameter("customer_num");
            String discount_code = request.getParameter("discount_code");
            String zip = request.getParameter("zip");
            String name = new String(
                            request.getParameter("name").getBytes("8859_1"),
                            "JISAutoDetect");
            String phone = request.getParameter("phone");

            StringBuffer buf = new StringBuffer();
            buf.append("INSERT INTO CUSTOMER_TBL (");
            buf.append("CUSTOMER_NUM, DISCOUNT_CODE, ZIP, NAME, PHONE) ");
            buf.append("VALUES (");
            buf.append(customer_num);
            buf.append(",'");
            buf.append(discount_code);
            buf.append("','");
            buf.append(zip);
            buf.append("','");
            buf.append(name);
            buf.append("','");
            buf.append(phone);
            buf.append("')");
            stmt.executeUpdate(buf.toString());

            try { stmt.close(); } catch (Exception e) {}
            try { con.close(); } catch (Exception e) {}

        } catch (Exception e) {
            e.printStackTrace();
        }
%>

まず、必要な変数の初期化をおこなう。

      Connection con = null;
      Statement stmt = null;

次に、try節の中では、データベースに接続するConnectionオブジェクト の取得をおこなう。ここでは、接続するデータベースのURLを "jdbc:pointbase:server://localhost/sample"、ユーザ名が"PBPUBLIC"を、 パスワードを"PBPUBLIC"とする。

       con = DriverManager.getConnection(
           "jdbc:pointbase:server://localhost/sample",
           "PBPUBLIC", "PBPUBLIC");
それから、データベース操作を行うためのStatementオブジェクトの取得 をおこなう。

       stmt = con.createStatement();

さらに、データベース操作に必要な値をrequestオブジェクトから 取得する。

      String customer_num = request.getParameter("customer_num");
      String discount_code = request.getParameter("discount_code");
      String zip = request.getParameter("zip");
      String name = new String(
                      request.getParameter("name").getBytes("8859_1"),
                      "JISAutoDetect");
      String phone = request.getParameter("phone");

そして、実行するためのSQL文(Insert文)を作成する。

         StringBuffer buf = new StringBuffer();
         buf.append("INSERT INTO CUSTOMER_TBL (");
         buf.append("CUSTOMER_NUM, DISCOUNT_CODE, ZIP, NAME, PHONE) ");
         buf.append("VALUES (");
         buf.append(customer_num);
         buf.append(",'");
         buf.append(discount_code);
         buf.append("','");
         buf.append(zip);
         buf.append("','");
         buf.append(name);
         buf.append("','");
         buf.append(phone);
         buf.append("')");

上記で作成されたSQL文を実行するために、以下のような 処理をおこなう。

      stmt.executeUpdate(buf.toString());

以下では、データベースの後処理をおこなう。 finally節では、最終的におこなわれるデータベースとの接続が クローズが記述されている。

   try { stmt.close(); } catch (Exception e) {}
    try { con.close(); } catch (Exception e) {}
    } catch (Exception e) {
         e.printStackTrace();
    }
%>

そして、forwardアクションを用いて、データベースを検索する JSPプログラムJdbcCustomerTable.jspを呼び出す。

         <jsp:forward page="JdbcCustomerTable.jsp" />

ブラウザに出力されるHTML文章のtableタグ、bodyタグ、 htmlタグのそれぞれの終了タグを指定している。

        </table>
</body>
</html>

データの削除

以下のJdbcDelete.htmlでは、Formタグのaction属性の値には、 送信ボタンが押された時に、テキスト入力フィールドに入力された文字列を JSPプログラムであるJdbcDelete.jspに渡すことを指定している。

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<HTML>
  <HEAD>
    <TITLE>データベースからの削除</TITLE>
  </HEAD>
  <BODY>
  <FORM method=POST action='JdbcDelete.jsp'>
    <TABLE border='1'>
      <TR><TH>CUSTOMER_NUM</TH><TD><INPUT type=text name='customer_num'></TD></TR>
      <TR><TD><INPUT type=submit value='送信'></TD></TR>
    </TABLE>
  </FORM>
  </BODY>
</HTML>

次のプログラム JdbcDelete.jsp は、指定したWebサーバ下の ディレクトリ(アプリケーションのルートディレクトリ)下に 格納されているJSPファイルを実行することで、データベースのデータを削除 した結果をブラウザ上にテキスト表示するプログラムである。

<%@page contentType="text/html; charset=Shift_JIS" pageEncoding="Shift_JIS"%>
<%@page import="java.sql.*"%>
<%!
// サーブレットのinitメソッドに相当
public void jspInit() {
    try {
        // JDBCドライバをロード
        Class.forName("com.pointbase.jdbc.jdbcUniversalDriver");
    } catch (Exception e) {
        e.printStackTrace();
    }
}
%>

<html>
<head><title>CUSTOMER_TBLテーブルのDelete(JSP版)</title></head>

<body>
<P>JSPによるデータベースのDelete</P>

<%
        Connection con = null;
        Statement stmt = null;
        try {
            con = DriverManager.getConnection(
                "jdbc:pointbase:server://localhost/sample",
                "PBPUBLIC", "PBPUBLIC");

            stmt = con.createStatement();

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

            StringBuffer buf = new StringBuffer();
            buf.append("DELETE FROM CUSTOMER_TBL ");
            buf.append("WHERE CUSTOMER_NUM = ");
            buf.append(customer_num);
            stmt.executeUpdate(buf.toString());
            
            try { stmt.close(); } catch (Exception e) {}
            try { con.close(); } catch (Exception e) {}

        } catch (Exception e) {
            e.printStackTrace();
        }
%>

<jsp:forward page="JdbcCustomerTable.jsp" />
</body>
</html>

プログラム JdbcDelete.jspの説明

<%@page contentType="text/html; charset=Shift_JIS" pageEncoding="Shift_JIS"%>
は、pageディレクティブ(<%@page 〜%>)であり、JSPファイルを実行するJSP コンテナに対する指示を表す。この指示は、JSPからServletを自動的に変換・実行する ために用いられる。このpageディレクティブでは、JSPが出力するデータ形式 (contentType="text/html")、そこで使う文字コード(charset="Shift_JIS")と、 ソースコードの文字コード(pageEncoding="Shift_JIS")をそれぞれ指定している。

<%@page import="java.sql.*"%>
も、pageディレクティブ(<%@page 〜%>)であり、JDBC APIを 構成するクラスライブラリ(パッケージ)を使えるように宣言している。

<%! 〜 %>により、以下のようなjspInitメソッドが定義される。 jspInitメソッドは、SunONEに組み込まれたデータベース管理システム PointBaseのJDBCドライバのロードをおこなう。JDBCドライバは、 PointBase用のcom.pointbase.jdbc.jdbcUniversalDriverを用いる。

<%!
// サーブレットのinitメソッドに相当
public void jspInit() {
    try {
        // JDBCドライバをロード
        Class.forName("com.pointbase.jdbc.jdbcUniversalDriver");
    } catch (Exception e) {
        e.printStackTrace();
    }
}
%>

以下は、SQLによるデータベースの削除操作の結果を、HTML形式で 出力・表示する部分である。

<html>
<head><title>CUSTOMER_TBLテーブルのDelete(JSP版)</title></head>

<body>
<P>JSPによるデータベースのDelete</P>

<%
        Connection con = null;
        Statement stmt = null;
        try {
            con = DriverManager.getConnection(
                "jdbc:pointbase:server://localhost/sample",
                "PBPUBLIC", "PBPUBLIC");

            stmt = con.createStatement();

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

            StringBuffer buf = new StringBuffer();
            buf.append("DELETE FROM CUSTOMER_TBL ");
            buf.append("WHERE CUSTOMER_NUM = ");
            buf.append(customer_num);
            stmt.executeUpdate(buf.toString());
            
            try { stmt.close(); } catch (Exception e) {}
            try { con.close(); } catch (Exception e) {}

        } catch (Exception e) {
            e.printStackTrace();
        }
%>

<jsp:forward page="JdbcCustomerTable.jsp" />
</body>
</html>

次に、スクリプトレットにより、本プログラムの主処理が以下のようにおこなわれる。

<%
        Connection con = null;
        Statement stmt = null;
        try {
            con = DriverManager.getConnection(
                "jdbc:pointbase:server://localhost/sample",
                "PBPUBLIC", "PBPUBLIC");

            stmt = con.createStatement();

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

            StringBuffer buf = new StringBuffer();
            buf.append("DELETE FROM CUSTOMER_TBL ");
            buf.append("WHERE CUSTOMER_NUM = ");
            buf.append(customer_num);
            stmt.executeUpdate(buf.toString());
            
            try { stmt.close(); } catch (Exception e) {}
            try { con.close(); } catch (Exception e) {}

        } catch (Exception e) {
            e.printStackTrace();
        }
%>

まず、必要な変数の初期化をおこなう。

      Connection con = null;
      Statement stmt = null;

try節の中では、データベースに接続するConnectionオブジェクトの取得 をおこなう。ここでは、接続するデータベースのURLを "jdbc:pointbase:server://localhost/sample"、ユーザ名が"PBPUBLIC"を、 パスワードを"PBPUBLIC"とする。

       con = DriverManager.getConnection(
           "jdbc:pointbase:server://localhost/sample",
           "PBPUBLIC", "PBPUBLIC");
それから、データベース操作を行うためのStatementオブジェクトの取得 をおこなう。

       stmt = con.createStatement();

さらに、データベースにから削除するためのキーを requestオブジェクトから取得する。

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

そして、実行するためのSQL文(Delete文)を作成する。

      StringBuffer buf = new StringBuffer();
      buf.append("DELETE FROM CUSTOMER_TBL ");
      buf.append("WHERE CUSTOMER_NUM = ");
      buf.append(customer_num);

上記で作成されたSQL文を実行して、結果を得るために、以下のような 処理をおこなう。

      stmt.executeUpdate(buf.toString());

以下では、データベースの後処理をおこなう。 finally節では、最終的におこなわれるデータベースとの接続が クローズが記述されている。

   try { stmt.close(); } catch (Exception e) {}
    try { con.close(); } catch (Exception e) {}
    } catch (Exception e) {
         e.printStackTrace();
    }
%>

そして、forwardアクションを用いて、データベースを検索する JSPプログラムJdbcCustomerTable.jspを呼び出す。

         <jsp:forward page="JdbcCustomerTable.jsp" />

ブラウザに出力されるHTML文章のtableタグ、bodyタグ、 htmlタグのそれぞれの終了タグを指定している。

        </table>
</body>
</html>

問題-1

Sun ONEを使って、上のプログラムJdbcCustomerTable.jsp を実行してみよ。

問題-2

上のプログラムJdbcCustomerTable.jspを参考にして、 "CUSTOMER_TABLE"テーブルを、昇順に顧客番号でソートし、顧客番号、 名前、電話番号からなるテーブルを表示するプログラム JdbcCustomerTable1.jspを作成・実行し、その結果を表示せよ。

問題-3

上のプログラムJdbcCustomerTable.jspを参考にして、 "CUSTOMER_TABLE"テーブルから名前が"H"ではじまるレコードを検索し、 その結果を、顧客番号、名前、電話番号からなるテーブルとして表示する プログラムJdbcCustomerTable2.jspを作成・実行し、 その結果を表示せよ。なお、このプログラムでは、表示されたテーブルの レコード数も求めるものとする。

問題-4

上のプログラムJdbcCustomerTable.jspを参考にして、 "CUSTOMER_TABLE"テーブルから、電話番号が"313-......."のレコードを 検索し、さらに顧客番号で昇順にソートした結果を、顧客番号、名前、電話番号から なるテーブルとして表示するプログラムJdbcCustomerTable3.jsp を作成・実行し、その結果を表示せよ。

問題-5

上のプログラムJdbcUpdate.jspの動作を説明せよ。

問題-6

上のプログラムJdbcInsert.jspの動作を説明せよ。

問題-7

上のプログラムJdbcDelete.jspの動作を説明せよ。

システムプログラミング演習


nagai@rsch.tuis.ac.jp (Based upon mizutani@rsch.tuis.ac.jp's style sheets & results)