2010年8月14日土曜日

JSP(データベースPostgreSQ)サンプル

<%@ page contentType="text/html; charset=Shift_JIS" %>
<%@ page import="java.sql.*" %>
<%
Connection con = null;
Statement stmt = null;
try {
// ドライバクラスをロード
//Class.forName("org.gjt.mm.mysql.Driver");
Class.forName("org.postgresql.Driver"); // PostgreSQLの場合

// データベースへ接続
//String url = "jdbc:mysql:///hellodb?useUnicode=true&characterEncoding=SJIS";
con =
DriverManager.getConnection("jdbc:postgresql:db001",
"postgres",
"zxcvvcxz"); // PostgreSQLの場合

//con = DriverManager.getConnection(url);
// ステートメントオブジェクトを生成
stmt = con.createStatement();
// 全ての行を検索するSQL文を作成
String sql = "SELECT * FROM tbl001";
// クエリーを実行して結果セットを取得
ResultSet rs = stmt.executeQuery(sql);


session.setAttribute("AAAA","FF");
%>
<html>
<head>
<title>JSPでDB接続</title>
</head>
<body>
<table border="1">
<tr>
<th>NO</th>
<th>言語</th>
<th>メッセージ</th>
</tr>
<%
// 検索された行数分ループ
while(rs.next()){
%>
<tr>
<td><%=rs.getInt("rid") %></td>
<td><%=rs.getString("username") %></td>
<td><%=rs.getString("username") %></td>
</tr>
<%
} // end while
%>
</table>
</body>
</html>
<%
} catch (Exception e) {
out.println("<font color=red><h3>エラー!</h3></font>" + e);
e.printStackTrace();
} finally {
// データベースへの接続をクローズします
try {
if (stmt!=null) {
stmt.close();
}
if (con!=null) {
con.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
%>

0 件のコメント:

コメントを投稿