データの登録
13.4 データの登録
本節では、WebアプリケーションからJDBCを利用してMariaDBデータベースへデータを登録する方法について学習します。
データを登録するプログラム
入力フォームから登録する一連の情報を入力し、その情報をJDBCを利用してデータベースへ登録します。
実行結果

アプリケーション構成

① ソース・フォルダ :web_basic/src/main/java
② パッケージ :ch13
③ 名前 :AccountDao4
➢ AccountDao4.java
3 | import java.sql.Connection; |
4 | import java.sql.DriverManager; |
5 | import java.sql.SQLException; |
6 | import java.sql.Statement; |
8 | public class AccountDao4 { |
10 | //接続用の情報をフィールドに定数として定義 |
11 | private static String RDB_DRIVE = "org.mariadb.jdbc.Driver"; |
12 | private static String URL = "jdbc:mariadb://localhost/accountdb"; |
13 | private static String USER = "root"; |
14 | private static String PASS = "root123"; |
17 | public static Connection getConnection(){ |
19 | Class.forName(RDB_DRIVE); |
20 | Connection con = DriverManager.getConnection(URL, USER, PASS); |
23 | throw new IllegalStateException(e); |
28 | public int insert(AccountInfo accountinfo){ |
30 | Connection con = null; |
37 | String sql = "INSERT INTO account VALUES('" |
38 | + accountinfo.getId() + "','" |
39 | + accountinfo.getName() + "','" |
40 | + accountinfo.getEmail() + "','" |
41 | + accountinfo.getAuthority() + "')"; |
44 | con = getConnection(); |
45 | smt = con.createStatement(); |
48 | count = smt.executeUpdate(sql); |
51 | throw new IllegalStateException(e); |
55 | try{smt.close();}catch(SQLException ignore){} |
58 | try{con.close();}catch(SQLException ignore){} |
① 親フォルダの入力または選択 :web_basic/src/main/webapp/view/ch13
② ファイル名 :insertForm.jsp
③ アクセスURL :http://localhost:8080/web_basic/view/ch13/insertForm.jsp
➢ insertForm.jsp
1 | <%@page contentType="text/html; charset=UTF-8"%> |
5 | < title >データを登録する</ title > |
8 | < div style = "text-align:center" > |
9 | < h2 style = "text-align:center" >登録データ入力画面</ h2 > |
10 | < hr style = "height:3; background-color:#0000ff" /> |
13 | < form action="<%=request.getContextPath() %>/InsertServlet"> |
14 | < table style = "margin:0 auto" > |
16 | < td style = "width:60" >ID</ td > |
17 | < td >< input type = text size = "30" name = "id" ></ input ></ td > |
20 | < td style = "width:60" >名前</ td > |
21 | < td >< input type = text size = "30" name = "name" ></ input ></ td > |
24 | < td style = "width:70" >アドレス</ td > |
25 | < td >< input type = text size = "30" name = "email" ></ input ></ td > |
28 | < td style = "width:60" >権限</ td > |
30 | < select name = "authority" > |
31 | < option value = "管理者" >管理者</ option > |
32 | < option value = "一般" >一般</ option > |
37 | < td colspan = 2 style = "text-align:center" > |
38 | < input type = "submit" value = "登録" > |
① ソース・フォルダ :web_basic/src/main/java
② パッケージ :ch13
③ 名前 :InsertServlet
④ スーパークラス :jakarta.servlet.http.HttpServlet
⑤ アクセスURL :insertForm.jspからの画面遷移でアクセスされる
➢ InsertServlet.java
3 | import java.io.IOException; |
5 | import jakarta.servlet.ServletException; |
6 | import jakarta.servlet.annotation.WebServlet; |
7 | import jakarta.servlet.http.HttpServlet; |
8 | import jakarta.servlet.http.HttpServletRequest; |
9 | import jakarta.servlet.http.HttpServletResponse; |
11 | @WebServlet("/InsertServlet") |
12 | public class InsertServlet extends HttpServlet{ |
13 | public void doGet(HttpServletRequest request ,HttpServletResponse response) |
14 | throws ServletException ,IOException{ |
20 | request.setCharacterEncoding("UTF-8"); |
23 | AccountInfo accountinfo = new AccountInfo(); |
26 | accountinfo.setId(request.getParameter("id")); |
27 | accountinfo.setName(request.getParameter("name")); |
28 | accountinfo.setEmail(request.getParameter("email")); |
29 | accountinfo.setAuthority(request.getParameter("authority")); |
32 | AccountDao4 objDao4 = new AccountDao4(); |
35 | int count = objDao4.insert(accountinfo); |
37 | //登録された件数を持ってinsertReceipt.jspにフォワード |
38 | request.setAttribute("count", count); |
40 | }catch (IllegalStateException e) { |
41 | error ="DB接続エラーの為、登録できませんでした。"; |
44 | error ="予期せぬエラーが発生しました。< br >"+e; |
47 | request.setAttribute("error", error); |
48 | request.getRequestDispatcher("/view/ch13/insertReceipt.jsp").forward(request, response); |
① 親フォルダの入力または選択 :web_basic/src/main/webapp/view/ch13
② ファイル名 :insertReceipt.jsp
③ アクセスURL :InsertServlet.javaからの画面遷移でアクセスされる
➢ insertReceipt.jsp
1 | <%@page contentType="text/html; charset=UTF-8"%> |
4 | Integer count = (Integer)request.getAttribute("count"); |
5 | String error = (String)request.getAttribute("error"); |
10 | < title >データを登録する</ title > |
13 | < div style = "text-align:center" > |
14 | < h2 style = "text-align:center" >検索ID入力画面</ h2 > |
15 | < hr style = "height:3; background-color:#0000ff" /> |
18 | <% if(count != null){ %> |
19 | <%= count%>件のデータを登録しました。 |
解説
今回のプログラムでは、登録情報を入力するinsertForm.jspから入力されたデータをInsertServlet.java内の23行目から26行目で受け取り、アカウント情報を管理するオブジェクトへセットします。
23:accountinfo.setId(request.getParameter("id"));
24:accountinfo.setName(request.getParameter("name"));
25:accountinfo.setEmail(request.getParameter("email"));
26:accountinfo.setAuthority(request.getParameter("authority"));
その後、32行目でDAOクラス内に定義されたinsert()メソッドにアカウント情報を管理するオブジェクトを渡し、データベースへ登録を行います。
32:int count = objDao4.insert(accountinfo);
insert()メソッドは登録件数が戻り値として定義されており、戻り値として受け取った登録件数を34行目でリクエストスコープへ登録しています。
insertReceipt.jspではリクエストスコープへ登録された件数を取得し、画面へ表示しています。
19:<%= count%>件のデータを登録しました。
今回のプログラムでは、登録された件数のみが表示されるため、データが正しく登録されたかどうかを確認することができません。データを確認したい場合は、13.3.1項で作成した一覧を表示するプログラムを実行してください。

図 13.4.1 データ登録後の一覧表示
次の節では、簡単なデータを更新するWebアプリケーションを作成しデータの更新方法を学習します。
データ登録時の注意点
MySQLに作成したaccountテーブルは、IDの情報が主キーとして設定されています。そのため、データを登録する場合はIDが重複しないように注意する必要があります。
誤って重複したIDで登録を行うと、以下のようにエラーが発生します。

NEXT>> 13.5 データの更新