データベースのテーブルの作成
MySQLをインストールすると、testという名前のデータベース領域がデフォルトで作られています。その領域にpersonというテーブルを作成し、5人の人名を登録します。grant all on test.* to Mulder@localhost identified by 'TrustNo1';
use test;
create table person(
id INT auto_increment PRIMARY KEY,
name VARCHAR(255)
);
INSERT INTO person SET name='鈴木一朗';
INSERT INTO person SET name='田宮二郎';
INSERT INTO person SET name='北島三郎';
INSERT INTO person SET name='伊東四朗';
INSERT INTO person SET name='野口五郎';
最初の行はMySQLにMulderというユーザを登録し、testデータベース領域へのアクセス権(all)を設定しています。use test;
create table person(
id INT auto_increment PRIMARY KEY,
name VARCHAR(255)
);
INSERT INTO person SET name='鈴木一朗';
INSERT INTO person SET name='田宮二郎';
INSERT INTO person SET name='北島三郎';
INSERT INTO person SET name='伊東四朗';
INSERT INTO person SET name='野口五郎';
2行目でtestデータベース領域を選択し、3行目以降でテーブルを作成してデータを挿入しています。
テーブルの内容を一覧表示するJSP
~program/test/JSPディレクトリにdbtest.jspというファイルを作り、次のような内容を保存します。<%@ page pageEncoding="utf-8"%>
<%@ page import="java.sql.*"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<HTML>
<HEAD>
<TITLE>Simple BBS</TITLE>
</HEAD>
<BODY>
<%
Class.forName("com.mysql.jdbc.Driver");
String strConn = "jdbc:mysql://localhost/test"
+"?user=Mulder&password=TrustNo1"
+"&useUnicode=true&characterEncoding=utf-8";
Connection conn = DriverManager.getConnection(strConn);
String strSql = "SELECT * FROM person";
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(strSql);
while(rs.next()){
%>
<%=rs.getInt("id")%>:<%=rs.getString("name")%><BR>
<%}%>
</BODY>
</HTML>
ブラウザでhttp://localhost/test/dbtest.jsp にアクセスします。<%@ page import="java.sql.*"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<HTML>
<HEAD>
<TITLE>Simple BBS</TITLE>
</HEAD>
<BODY>
<%
Class.forName("com.mysql.jdbc.Driver");
String strConn = "jdbc:mysql://localhost/test"
+"?user=Mulder&password=TrustNo1"
+"&useUnicode=true&characterEncoding=utf-8";
Connection conn = DriverManager.getConnection(strConn);
String strSql = "SELECT * FROM person";
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(strSql);
while(rs.next()){
%>
<%=rs.getInt("id")%>:<%=rs.getString("name")%><BR>
<%}%>
</BODY>
</HTML>

データベース連携テスト
投稿:竹形 誠司[takegata]/2009年 03月 30日 04時 38分
/更新:2009年 03月 30日 04時 38分