サンプルコード3(JSP)

今度は、JSPでJDBCを扱うサンプル。このプログラムは表の全レコードを表示するだけのものである。


jdbcJspSample.jsp


<%@ page import="java.sql.*" %>
<%@ page contentType="text/html; charset=EUC_JP" %>
<html>
<head>
<title>JDBCによるインデックス/索引システム(?)JSP版</title>
</head>
<body>
<% 
    Connection conn = null; 
    Statement stmt = null; 
    ResultSet rs = null; 
%>
<%! int i=0; %>

<!-- JDBCドライバーのロード -->
<% 
    try{ 
        Class.forName("org.postgresql.Driver"); 
        conn = DriverManager.getConnection(
            "jdbc:postgresql://サーバ名/データベース名", "ユーザ名", "パスワード"
        ); 
    } 
    catch( SQLException se ){ 
        System.out.println( se ); 
    } 
%>

<h3>JDBCによるインデックス/索引システム(?)JSP版 (見るだけ)</h3>
<hr>
<table align=center>

<!-- SQLの実行 -->
<% 
    try{ 
        stmt = conn.createStatement();  
        rs = stmt.executeQuery(
            "SELECT * FROM t99xxxxx_tbl1"
        ); 
        while(rs.next()){
            String button0 = rs.getString("button0");
            String name0 = rs.getString("name0");
            String textarea0 = rs.getString("textarea0");
            out.println("<tr><td><b>URL:</b></td>");
            out.println("<td><b><a href=\""+ name0 +"\">"
                                  + name0 +"</a></b></td></tr>");
            out.println("<tr><td>概念:</td>");
            out.println("<td>" + button0 + "</td></tr>");
            out.println("<tr><td>コメント:</td>");
            out.println("<td>" + textarea0 + "</td></tr>");
            out.println("<tr><td colspan=2><hr></td></tr>");
        }
    rs.close();
    stmt.close();
    conn.close();
    } 
    catch( SQLException se ){ 
        System.out.println( se ); 
    } finally{
        try{
            if(rs != null) rs.close();
            if(stmt != null) stmt.close();
            if(conn != null) conn.close();
         }catch(Exception e){
             e.printStackTrace();
         }
    }
%>
</table>
</body>
</html>



実行結果

こんな感じ




→さらなるサンプル
←もどる
ホームへ