DataBaseに接続 (JDBC & JSP)

データを入力


  1. 「ボタンを押すとデータベースへ接続するページ」を作る。
    作るファイルは2つ
    ファイル名 機能
    jsp_database.html 入力フィールドと「データを入力」ボタンを配置したページ
    jsp_insert_data.jsp データをデータベースに追加するJSP
    データベースに追加できたときは、"1 line insert successfully."
    失敗したときは"Data insert fail"

  2. 入力フィールド
    データの入力には、inputタグを使う。typeはtext,nameは任意の名前を付けてよいが、可読性を考慮し、フィールド名と同じにする。
    内容 データベース 入力ページ
    フィールド名 tag type name 入力する値
    出席番号 id int input text id 整数
    氏名 name text input text name 文字列

  3. 「テーブルをつくる」ボタン
    <form method="POST" action="http://localhost:8080/jsp_database/jsp_insert_data.jsp">
      <fieldset>
      <legend>データを入力する</legend>
        出席番号 <input size="20" type="text" name="id"><br>
        氏  名 <input size="20" type="text" name="name"> <br>
      </fieldset>
    </form>
      

  4. データを入力するJSP
    【注意】
    <%@ page contentType="text/html; charset=UTF-8" %>
    <%@ page import="java.sql.*" %> 
    <html>
    <head>
      <title>DataBaseに接続 (JDBC & JSP)接続テスト</title>
    </title>
    <%
        String msg="" ;
        try {
          String id   = request.getParameter("id")   ;// 出席番号を取得
          String name = request.getParameter("name") ;// 氏名を取得
          name = new String( name.getBytes("8859_1"),"EUC_JP") ; //日本語の処理
    
          Class.forName("org.postgresql.Driver");
          Connection con = DriverManager.getConnection( "jdbc:postgresql://10.30.2.29:5432/j00300_01","j00300","hnct2004") ;
          Statement st = con.createStatement() ;
          String sql = "INSERT INTO sample VALUES (" + id +  "," + name +");" ;
          int result = st.executeUpdate(sql) ;
    
          msg=Integer.toString(result) + "line insert successfully.<br>" ;
          msg += "id="+ id + "&amp; name=" + name ;
        }
        catch (Exception ex) {
          msg = "TABLE creation fail.<br>" ;
          msg += ex.toString();
          msg += "<br>" ;
          msg += "id="+ id + "&amp; name=" + name ;
        }
    %>
    
    <body>
    <h1>DataBaseに接続 (JDBC &amp; JSP)テーブルをつくる</h1>
    <hr>
    <%= msg %><br><br>
    <hr>
    <a href=jsp_database.html>DataBaseに接続 (JDBC & JSP)</a>
    </body>
    </html>
    

eclipse logoEclipse DataBaseに接続 (JDBC & JSP)