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

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

1. データベースの検索

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

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

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Fruitテーブルの内容(JSP版)</title>
</head>

<body>
<P>JSPによるデータベースのアクセス</P>
<table border='1'><tr><th>NO</th><th>NAME</th><th>PRICE</th></tr>

<%
        // データベースへのアクセス開始
        Connection con = null;
        Statement stmt = null;
        ResultSet rs = null;
        try {
            // データベースに接続するConnectionオブジェクトの取得
            con = DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "tuis2019system");
            // データベース操作を行うためのStatementオブジェクトの取得
            stmt = con.createStatement();
            // SQL()を実行して、結果を得る
            rs = stmt.executeQuery("select no, name, price from fruit");

            // 得られた結果をレコードごとに表示
            while (rs.next()) {
%>
                <tr>
                <%-- レコードのNOフィールドを表示 --%>
                <td><%= rs.getInt("no")%></td>
                <%-- レコードのNAMEフィールドを表示 --%>
                <td><%= rs.getString("name")%></td>
                <%-- レコードのPRICEフィールドを表示 --%>
                <td><%= rs.getInt("price")%></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ファイルJdbcFruitTable.jspを実行する。 そうすると、指定されたデータベースに接続され、SQL文により 検索がおこなわれ、その結果がブラウザ上に表示される。

プログラム JdbcFruitTable.jsp の説明

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

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

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

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

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

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Fruitテーブルの内容(JSP版)</title>
</head>

<body>
<P>JSPによるデータベースのアクセス</P>
<table border='1'><tr><th>NO</th><th>NAME</th><th>PRICE</th></tr>

<%
        // データベースへのアクセス開始
        Connection con = null;
        Statement stmt = null;
        ResultSet rs = null;
        try {
            // データベースに接続するConnectionオブジェクトの取得
            con = DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "tuis2019system");
            // データベース操作を行うためのStatementオブジェクトの取得
            stmt = con.createStatement();
            // SQL()を実行して、結果を得る
            rs = stmt.executeQuery("select no, name, price from fruit");

            // 得られた結果をレコードごとに表示
            while (rs.next()) {
%>
                <tr>
                <%-- レコードのNOフィールドを表示 --%>
                <td><%= rs.getInt("no")%></td>
                <%-- レコードのNAMEフィールドを表示 --%>
                <td><%= rs.getString("name")%></td>
                <%-- レコードのPRICEフィールドを表示 --%>
                <td><%= rs.getInt("price")%></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文書)の形式を指定している。データの更新結果は、 JdbcFruitTable.jspを呼び出すことで表示される。

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Fruitテーブルの内容(JSP版)</title>
</head>

<body>
<P>JSPによるデータベースのアクセス</P>
<table border='1'><tr><th>NO</th><th>NAME</th><th>PRICE</th></tr>

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

<%
        // データベースへのアクセス開始
        Connection con = null;
        Statement stmt = null;
        ResultSet rs = null;
        try {
            // データベースに接続するConnectionオブジェクトの取得
            con = DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "tuis2019system");
            // データベース操作を行うためのStatementオブジェクトの取得
            stmt = con.createStatement();
            // SQL()を実行して、結果を得る
            rs = stmt.executeQuery("select no, name, price from fruit");

            // 得られた結果をレコードごとに表示
            while (rs.next()) {
%>
                <tr>
                <%-- レコードのNOフィールドを表示 --%>
                <td><%= rs.getInt("no")%></td>
                <%-- レコードのNAMEフィールドを表示 --%>
                <td><%= rs.getString("name")%></td>
                <%-- レコードのPRICEフィールドを表示 --%>
                <td><%= rs.getInt("price")%></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:mysql://localhost/test"、ユーザ名が"root"を、パスワードを"tuis2019system"としている。

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

       stmt = con.createStatement();

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

       rs = stmt.executeQuery("select no, name, price from fruit");

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

            // 得られた結果をレコードごとに表示
            while (rs.next()) {
%>
                <tr>
                <%-- レコードのNOフィールドを表示 --%>
                <td><%= rs.getInt("no")%></td>
                <%-- レコードのNAMEフィールドを表示 --%>
                <td><%= rs.getString("name")%></td>
                <%-- レコードのPRICEフィールドを表示 --%>
                <td><%= rs.getInt("price")%></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>

2. データの更新

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

<!DOCTYPE>
<HTML>
  <HEAD>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <TITLE>データベースの変更</TITLE>
  </HEAD>
  <BODY>
  <FORM method=POST action='JdbcUpdate.jsp'>
    <TABLE border='1'>
      <TR><TH>NO</TH><TD><INPUT type=text name='no'/></TD></TR>
      <TR><TH>NAME</TH><TD><INPUT type=text name='name'/></TD></TR>
      <TR><TH>PRICE</TH><TD><INPUT type=text name='price'/></TD></TR>
      <TR><TD><INPUT type=submit value='送信'/></TD></TR>
    </TABLE>
  </FORM>
  </BODY>
</HTML>

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

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

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>FruitテーブルのUpdate(JSP版)</title>
</head>

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


<%
        Connection con = null;
        Statement stmt = null;
        try {
            con = DriverManager.getConnection("jdbc:mysql://localhost/test",  "root", "tuis2019system");

            stmt = con.createStatement();

            String no = request.getParameter("no");
            String name = request.getParameter("name");
            String price = request.getParameter("price");

            StringBuffer buf = new StringBuffer();
            buf.append("update fruit set ");
            buf.append("name = '");
            buf.append(name);
            buf.append("', price = '");
            buf.append(price);
            buf.append("' where no = ");
            buf.append(no);
            stmt.executeUpdate(buf.toString());
            
            try { stmt.close(); } catch (Exception e) {}
            try { con.close(); } catch (Exception e) {}

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

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

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

プログラム JdbcUpdate.jsp の説明

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

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

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

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

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

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>FruitテーブルのUpdate(JSP版)</title>
</head>

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


<%
        Connection con = null;
        Statement stmt = null;
        try {
            con = DriverManager.getConnection("jdbc:mysql://localhost/test",  "root", "tuis2019system");

            stmt = con.createStatement();

            String no = request.getParameter("no");
            String name = request.getParameter("name");
            String price = request.getParameter("price");

            StringBuffer buf = new StringBuffer();
            buf.append("update fruit set ");
            buf.append("name = '");
            buf.append(name);
            buf.append("', price = '");
            buf.append(price);
            buf.append("' where no = ");
            buf.append(no);
            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="JdbcFruitTable.jsp" />
</body>
</html>

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

<%
        Connection con = null;
        Statement stmt = null;
        try {
            con = DriverManager.getConnection("jdbc:mysql//localhost/test", "root", "tuis2019system");

            stmt = con.createStatement();

            String no = request.getParameter("no");
            String name = request.getParameter("name");
            String price = request.getParameter("price");

            StringBuffer buf = new StringBuffer();
            buf.append("update fruit set ");
            buf.append("name = '");
            buf.append(name);
            buf.append("', price = '");
            buf.append(price);
            buf.append("' where no = ");
            buf.append(no);
            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:mysql://localhost/test"、ユーザ名が"root"を、パスワードを"tuis2019system"とする。

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

       stmt = con.createStatement();

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

      String no = request.getParameter("no");
      String name = request.getParameter("name");
      String price = request.getParameter("price");

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

         StringBuffer buf = new StringBuffer();
         buf.append("update fruit set ");
         buf.append("name = '");
         buf.append(name);
         buf.append("', price = '");
         buf.append(price);
         buf.append("' where no = ");
         buf.append(no);

上記で作成された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プログラムJdbcFruitTable.jspを呼び出す。

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

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

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

3. データの追加

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

<!DOCTYPE HTML>
<HTML>
  <HEAD>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <TITLE>データベースへの追加</TITLE>
  </HEAD>
  <BODY>
  <FORM method=POST action='JdbcInsert.jsp'>
    <TABLE border='1'>
      <TR><TH>NO</TH><TD><INPUT type=text name='no'/></TD></TR>
      <TR><TH>NAME</TH><TD><INPUT type=text name='name'/></TD></TR>
      <TR><TH>PRICE</TH><TD><INPUT type=text name='price'/></TD></TR>
      <TR><TD><INPUT type=submit value='送信'/></TD></TR>
    </TABLE>
  </FORM>
  </BODY>
</HTML>

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

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

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>CUSTOMER_TBLテーブルのInsert(JSP版)</title>
</head>

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

<%
        Connection con = null;
        Statement stmt = null;
        try {
            con = DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "tuis2019system");

            stmt = con.createStatement();

            String no = request.getParameter("no");
            String name = request.getParameter("name");
            String price = request.getParameter("price");

            StringBuffer buf = new StringBuffer();
            buf.append("insert into fruit (");
            buf.append("no, name, price) ");
            buf.append("values (");
            buf.append(no);
            buf.append(",'");
            buf.append(name);
            buf.append("','");
            buf.append(price);
            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="JdbcFruitTable.jsp" />

</body>
</html>

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

プログラム JdbcInsert.jsp の説明

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

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

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

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

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

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>FruitテーブルのInsert(JSP版)</title>
</head>

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

<%
        Connection con = null;
        Statement stmt = null;
        try {
            con = DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "tuis2019system");

            stmt = con.createStatement();

            String no = request.getParameter("no");
            String name = request.getParameter("name");
            String price = request.getParameter("price");

            StringBuffer buf = new StringBuffer();
            buf.append("insert into fruit (");
            buf.append("no, name, price) ");
            buf.append("values (");
            buf.append(no);
            buf.append(",'");
            buf.append(name);
            buf.append("','");
            buf.append(price);
            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="JdbcFruitTable.jsp" />

</body>
</html>

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

<%
        Connection con = null;
        Statement stmt = null;
        try {
            con = DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "tuis2019system");

            stmt = con.createStatement();

            String no = request.getParameter("no");
            String name = request.getParameter("name");
            String price = request.getParameter("price");

            StringBuffer buf = new StringBuffer();
            buf.append("insert into fruit (");
            buf.append("no, name, price) ");
            buf.append("values (");
            buf.append(no);
            buf.append(",'");
            buf.append(name);
            buf.append("','");
            buf.append(price);
            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:mysql://localhost/test"、ユーザ名が"root"を、 パスワードを"tuis2019system"とする。

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

       stmt = con.createStatement();

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

      String no = request.getParameter("no");
      String name = request.getParameter("name");
      String price = request.getParameter("price");

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

         StringBuffer buf = new StringBuffer();
         buf.append("insert into fruit (");
         buf.append("no, name, price) ");
         buf.append("values (");
         buf.append(no);
         buf.append(",'");
         buf.append(name);
         buf.append("','");
         buf.append(price);
         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プログラムJdbcFruitTable.jspを呼び出す。

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

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

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

4. データの削除

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

<!DOCTYPE HTML>
<HTML>
  <HEAD>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <TITLE>データベースからの削除</TITLE>
  </HEAD>
  <BODY>
  <FORM method=POST action='JdbcDelete.jsp'>
    <TABLE border='1'>
      <TR><TH>NO</TH><TD><INPUT type=text name='no'/></TD></TR>
      <TR><TD><INPUT type=submit value='送信'/></TD></TR>
    </TABLE>
  </FORM>
  </BODY>
</HTML>

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

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

<!DOCTYPE html>
<html>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<head>
<title>FruitテーブルのDelete(JSP版)</title>
</head>

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

<%
        Connection con = null;
        Statement stmt = null;
        try {
            con = DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "tuis2019system");

            stmt = con.createStatement();

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

            StringBuffer buf = new StringBuffer();
            buf.append("delete from fruit ");
            buf.append("where no = ");
            buf.append(no);
            stmt.executeUpdate(buf.toString());
            
            try { stmt.close(); } catch (Exception e) {}
            try { con.close(); } catch (Exception e) {}

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

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

プログラム JdbcDelete.jspの説明

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

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

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

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

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

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>FruitテーブルのDelete(JSP版)</title>
</head>

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

<%
        Connection con = null;
        Statement stmt = null;
        try {
            con = DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "tuis2019system");

            stmt = con.createStatement();

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

            StringBuffer buf = new StringBuffer();
            buf.append("delete from fruit ");
            buf.append("where no = ");
            buf.append(no);
            stmt.executeUpdate(buf.toString());
            
            try { stmt.close(); } catch (Exception e) {}
            try { con.close(); } catch (Exception e) {}

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

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

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

<%
        Connection con = null;
        Statement stmt = null;
        try {
            con = DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "tuis2019system");

            stmt = con.createStatement();

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

            StringBuffer buf = new StringBuffer();
            buf.append("delete from fruit ");
            buf.append("where no = ");
            buf.append(no);
            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:mysql://localhost/test"、ユーザ名が"root"を、 パスワードを"tuis2019system"とする。

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

       stmt = con.createStatement();

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

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

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

      StringBuffer buf = new StringBuffer();
      buf.append("delete from fruit ");
      buf.append("where no = ");
      buf.append(no);

上記で作成された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プログラムJdbcFruitTable.jspを呼び出す。

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

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

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

5. 演習問題 

問題-1

NetBeansを使って、上のプログラムJdbcFruitTable.jsp を実行し、その結果を表示せよ。

問題-2

上のプログラムJdbcFruitTable.jspを参考にして、 "fruit"テーブルを、降順にnoでソートし、no、name、priceからなるテーブル を表示するプログラムJdbcFruitTable1.jspを作成・実行し、 その結果を表示せよ。

問題-3

上のプログラムJdbcFruitTable.jspを参考にして、 "fruit"テーブルからnameが"b"ではじまらないレコードを検索し、 その結果を、no、name、priceからなるテーブルとして表示する プログラムJdbcFruitTable2.jspを作成・実行し、 その結果を表示せよ。なお、このプログラムでは、表示されたテーブルの レコード数も求めるものとする。

問題-4

上のプログラムJdbcFruitTable.jspを参考にして、 "fruit"テーブルから、priceフィールドの値の合計と平均を求め、 その結果をテーブルとして表示するプログラムJdbcFruitTable3.jsp を作成・実行し、その結果を表示せよ。

問題-5

上のプログラムJdbcUpdate.jspを実行し、その結果を表示せよ。

問題-6

上のプログラムJdbcInsert.jspを実行し、その結果を表示せよ。

問題-7

上のプログラムJdbcDelete.jspを実行し、その結果を表示せよ。

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


Yasuo NAGAI