動作テスト用ファイル、PHP、Perl、Java、PostgreSQL、MySQL、DB、JSP、サーブレット - サンプル



●はじめに

・このページは、サーバ上でPHP、CGI、データベースなどの表示のテストをするための簡単なサンプルファイルの紹介です。
・Linux Fedora、RedHat、Apache、tomcatなどのシステム上での動作確認を行えます。
・新しい環境でウェブアプリケーションを動作させる場合、まず簡単なサンプルが動作するか試すことをオススメします。
・HTML
・Perl、Perl + PostgreSQL、Perl + MySQL
・PHP、PHP + PostgreSQL、PHP + MySQL
・Java、Java + PostgreSQL、Java + MySQL

●HTML / test.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>HTML TEST</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
</head>
<body>
<h2>HTMLテスト</h2>
</body>
</html>

●CGI(Perl) / test.cgi
#!/usr/bin/perl
print "Content-type: text/html\n\n";
print "<html><head><title>CGI-Perl TEST</title>\n";
print "<meta http-equiv='content-type' content='text/html; charset=utf-8'>\n";
print "</head><body><h2>CGI-Perlテスト</h2>\n";
print "</body></html>\n";
exit;

●CGI(Perl + PostgreSQL、use Pg) / perl_pg_postgres.cgi(CentOS 7及びFedora 22で動作しない)

 テキストで表示させたい方はこちらです。
#!/usr/bin/perl

use Pg;
use CGI::Carp qw(fatalsToBrowser);

$conn = &ConnectDB;
$tbl = "テーブル名";

print "Content-type: text/html\n\n";
print "<html><head><title>CGI-Perl usePg TEST</title>\n";
print "<meta http-equiv='content-type' content='text/html; charset=utf-8'>\n";
print "</head><body><h2>DB接続テスト(CGI-Perl usePg版)</h2>\n";

##### データ挿入 #####
#$sql1 = "insert into $tbl values('data1','data2','data3')";
#$sth1 = $conn->exec($sql1);

##### データ更新 #####
#$sql2 = "update $tbl set name='new_data' where name='old_data'";
#$sth2 = $conn->exec($sql2);

##### データ削除 #####
#$sql3 = "delete from $tbl where name='data'";
#$sth3 = $conn->exec($sql3);

##### データ表示 #####
$sql = "select * from $tbl";
$select = $conn ->exec($sql);
$check = $select->ntuples;

if($check != 0){
  for ($i=0;$i<$check;$i++){
    $row1 = $select->getvalue($i,0);
    $row2 = $select->getvalue($i,1);
    $row3 = $select->getvalue($i,2);
    print "$row1 / $row2 / $row3<br>\n";
  }
}

print "$errorMessage<br>\n";
print "$err</body></html>\n";

exit;

sub ConnectDB{
  $pghost = "localhost";
  $pgport = "5432";
  $pgoptions = "";
  $pgtty = "";
  $pgdbname = "データベース名";
  $pguser = "ユーザ名";
  $pgpwd = "パスワード";
  my($conn);
  $conn = Pg::setdbLogin($pghost, $pgport, $pgoptions, $pgtty, $pgdbname, $pguser, $pgpwd);
  if( $conn->status == PGRES_CONNECTION_BAD){
    $err = "接続失敗";
    $errorMessage = $conn->errorMessage
  }
  #$setencoding = $conn->exec("set client_encoding='UTF8';");
  return($conn);
}

●CGI(Perl + PostgreSQL、DBI:Pg) / perl_dbi_postgres.cgi

 テキストで表示させたい方はこちらです。
#!/usr/bin/perl

use DBI;
use CGI::Carp qw(fatalsToBrowser);

$conn = &ConnectDB;
$tbl = "テーブル名";

print "Content-type: text/html\n\n";
print "<html><head><title>CGI-Perl DBI:Pg TEST</title>\n";
print "<meta http-equiv='content-type' content='text/html; charset=utf-8'>\n";
print "</head><body><h2>DB接続テスト(CGI-Perl DBI:Pg版)</h2>\n";

##### データ挿入 #####
#$sql1 = "insert into $tbl values('data1','data2','data3')";
#$sth1 = $conn->prepare($sql1);
#$ref1 = $sth1 ->execute;

##### データ更新 #####
#$sql2 = "update $tbl set name='new_data' where name='old_data'";
#$sth2 = $conn->prepare($sql2);
#$ref2 = $sth2 ->execute;

##### データ削除 #####
#$sql3 = "delete from $tbl where name='data'";
#$sth3 = $conn->prepare($sql3);
#$ref3 = $sth3 ->execute;

##### データ表示 #####
$sql = "select * from $tbl";
$sth = $conn->prepare($sql);
$ref = $sth ->execute;

for($i=0;$i<$ref;$i++){
  ($row1,$row2,$row3) = $sth->fetchrow_array();
  print "$row1 / $row2 / $row3<br>\n";
}

$sth ->finish;
$conn->disconnect;

print "$err</body></html>\n";

exit;

sub ConnectDB{
  $dbname = 'データベース名';
  $host = 'localhost';
  $port = 5432;
  $username = 'ユーザ名';
  $password = '';

  $conn = DBI->connect("dbi:Pg:dbname=$dbname;host=$host;port=$port", "$username", "$password");

  if($conn->errstr != ""){
    $err = $conn->errstr;
  }
  #$setencoding = $conn->do("set client_encoding='UTF8';");
  return($conn);
}

●CGI(Perl + MySQL、DBI:MySQL) / perl_dbi_mysql.cgi

 テキストで表示させたい方はこちらです。
#!/usr/bin/perl

use DBI;
use CGI::Carp qw(fatalsToBrowser);

$conn = &ConnectDB;
$tbl = "テーブル名";

print "Content-type: text/html\n\n";
print "<html><head><title>CGI-Perl DBI:MySQL TEST</title>\n";
print "<meta http-equiv='content-type' content='text/html; charset=utf-8'>\n";
print "</head><body><h2>DB接続テスト(CGI-Perl DBI:MySQL版)</h2>\n";

##### データ挿入 #####
#$sql1 = "insert into $tbl values('data1','data2','data3')";
#$sth1 = $conn->prepare($sql1);
#$ref1 = $sth1 ->execute;

##### データ更新 #####
#$sql2 = "update $tbl set name='new_data' where name='old_data'";
#$sth2 = $conn->prepare($sql2);
#$ref2 = $sth2 ->execute;

##### データ削除 #####
#$sql3 = "delete from $tbl where name='data'";
#$sth3 = $conn->prepare($sql3);
#$ref3 = $sth3 ->execute;

##### データ表示 #####
$sql = "select * from $tbl";
$sth = $conn->prepare($sql);
$ref = $sth ->execute;

for($i=0;$i<$ref;$i++){
  ($row1,$row2,$row3) = $sth->fetchrow_array();
  print "$row1 / $row2 / $row3<br>\n";
}

$sth ->finish;
$conn->disconnect;

print "$err</body></html>\n";

exit;

sub ConnectDB{
  $dbname = 'データベース名';
  $host = 'localhost';
  $port = 3306;
  $username = 'ユーザ名';
  $password = '';

  $conn = DBI->connect("dbi:mysql:$dbname:$host:$port", "$username", "$password");

  if($conn->errstr != ""){
    $err = $conn->errstr;
  }
  return($conn);
}

●CGI(Ruby) / test.rb
#!/usr/bin/ruby
print "Content-type: text/html\n\n";
print "<html><head><title>CGI-Ruby TEST</title>\n";
print "<meta http-equiv='content-type' content='text/html; charset=utf-8'>\n";
print "</head><body><h2>CGI-Rubyテスト</h2>\n";
print "</body></html>\n";
exit;

●CGI(Ruby + PostgreSQL、use Pg) / ruby_pg_postgres.rb(CentOS 7及びFedora 22で動作しない)

 Fedora 20では動作しませんでしたので、「rubygems」の方を利用してください。

 テキストで表示させたい方はこちらです。
#!/usr/bin/ruby

require "postgres"

$hostname = "localhost"
$port = 5432
$dbname = "データベース名"
$username = "ユーザ名"
$password = "パスワード"
$encode = "UTF-8"
$tbl = "テーブル名"

print "Content-type: text/html\n\n";
print "<html><head><title>CGI-Ruby usePg TEST</title>\n";
print "<meta http-equiv='content-type' content='text/html; charset=utf-8'>\n";
print "</head><body><h2>DB接続テスト(CGI-Ruby usePg版)</h2>\n";

conn = PGconn.connect($hostname, $port, "", "", $dbname, $username, $password)

conn.set_client_encoding($encode)

##### データ挿入メソッド
def insert(conn)
$sql1 = "insert into " + $tbl + " values('data1','data2','data3');"
res = conn.exec($sql1)
end

##### データ更新メソッド
def update(conn)
$sql2 = "update " + $tbl + " set name='new_data' where name='old_data';"
res = conn.exec($sql2)
end

##### データ削除メソッド
def delete(conn)
$sql3 = "delete from " + $tbl + " where name='data';"
res = conn.exec($sql3)
end

##### データ表示メソッド
def view(conn)
$sql = "select * from " + $tbl + ";"
res = conn.exec($sql)
rows = res.num_tuples
cols = res.num_fields
for i in 0..rows-1 do
for j in 0..cols-1 do
print res.getvalue(i,j)," "
end
print "<br>\n"
end
end

begin
##### データ挿入
# insert(conn)

##### データの更新
# update(conn)

##### データの削除
# delete(conn)

##### データ表示
view(conn)

rescue => ex
conn.exec("ROLLBACK;")
print ex.message, "<br>\n"
ensure
conn.close()
end

print "</body></html>\n";


●CGI(Ruby + PostgreSQL、rubygems) / ruby_pg2_postgres.rb

 テキストで表示させたい方はこちらです。
#!/usr/bin/ruby

require "rubygems"
require "pg"

$hostname = "localhost"
$port = 5432
$dbname = "データベース名"
$username = "ユーザ名"
$password = "パスワード"
$encode = "UTF-8"
$tbl = "テーブル名"

print "Content-type: text/html\n\n";
print "<html><head><title>CGI-Ruby usePg TEST</title>\n";
print "<meta http-equiv='content-type' content='text/html; charset=utf-8'>\n";
print "</head><body><h2>DB接続テスト(CGI-Ruby rubygems版)</h2>\n";

conn = PGconn.connect($hostname, $port, "", "", $dbname, $username, $password)

conn.set_client_encoding($encode)

##### データ挿入メソッド
def insert(conn)
$sql1 = "insert into " + $tbl + " values('data1','data2','data3');"
res = conn.exec($sql1)
end

##### データ更新メソッド
def update(conn)
$sql2 = "update " + $tbl + " set name='new_data' where name='old_data';"
res = conn.exec($sql2)
end

##### データ削除メソッド
def delete(conn)
$sql3 = "delete from " + $tbl + " where name='data';"
res = conn.exec($sql3)
end

##### データ表示メソッド
def view(conn)
$sql = "select * from " + $tbl + ";"
res = conn.exec($sql)
rows = res.num_tuples
cols = res.num_fields
for i in 0..rows-1 do
for j in 0..cols-1 do
print res.getvalue(i,j)," "
end
print "<br>\n"
end
end

begin
##### データ挿入
# insert(conn)

##### データの更新
# update(conn)

##### データの削除
# delete(conn)

##### データ表示
view(conn)

rescue => ex
conn.exec("ROLLBACK;")
print ex.message, "<br>\n"
ensure
conn.close()
end

print "</body></html>\n";


●CGI(Ruby + PostgreSQL、DBI:Pg) / ruby_dbi_postgres.rb(CentOS 7及びFedora 22で動作しない)

 テキストで表示させたい方はこちらです。
#!/usr/bin/ruby

require "dbi"

$hostname = "localhost"
$port = 5432
$dbname = "データベース名"
$username = "ユーザ名"
$password = "パスワード"
$tbl = "テーブル名"

print "Content-type: text/html\n\n";
print "<html><head><title>CGI-Ruby DBI TEST</title>\n";
print "<meta http-equiv='content-type' content='text/html; charset=utf-8'>\n";
print "</head><body><h2>DB接続テスト(CGI-Ruby DBI版)</h2>\n";

begin
##### データ挿入 #####
#dbh = DBI.connect("dbi:pg:" + $dbname + ":" + $hostname, $username, $password)
#dbh.do("insert into " + $tbl + " (row1,row2,row3) values ('data1','data2','data3');")

##### データ更新 #####
#dbh = DBI.connect("dbi:pg:" + $dbname + ":" + $hostname, $username, $password)
#dbh.do("update " + $tbl + " set name = 'new_data' where name = 'old_data';")

##### データ削除 #####
#dbh = DBI.connect("dbi:pg:" + $dbname + ":" + $hostname, $username, $password)
#dbh.do("delete from " + $tbl + " where name = 'data';")

##### データ表示 #####
dbh = DBI.connect("dbi:pg:" + $dbname + ":" + $hostname, $username, $password)
$sql = "select * from " + $tbl + ";"
dbh.select_all($sql) do |row|
printf "%s, %s, %s<br>\n", row[0], row[1], row[2]
end

rescue DBI::DatabaseError => e
p "Error code: #{ e.err }<br>"
p "Error message: #{ e.errstr }<br>"
ensure
dbh.disconnect if dbh
end

print "</body></html>\n";

●CGI(Ruby + MySQL、DBI:MySQL、require "dbi") / ruby_dbi_mysql.rb

 Fedora 20では動作しませんでしたので、「require "mysql"」の方を利用してください。

 テキストで表示させたい方はこちらです。
#!/usr/bin/ruby

require "dbi"

$dbname = "データベース名"
$hostname = "localhost"
$username = "ユーザ名"
$password = "パスワード"
$tbl = "テーブル名"

print "Content-type: text/html\n\n";
print "<html><head><title>CGI-Ruby DBI TEST</title>\n";
print "<meta http-equiv='content-type' content='text/html; charset=utf-8'>\n";
print "</head><body><h2>DB接続テスト(CGI-Ruby DBI版)</h2>\n";

begin
##### データ挿入 #####
#dbh = DBI.connect("dbi:mysql:" + $dbname + ":" + $hostname, $username, $password)
#dbh.do("insert into " + $tbl + " (row1,row2,row3) values ('data1','data2','data3');")

##### データ更新 #####
#dbh = DBI.connect("dbi:mysql:" + $dbname + ":" + $hostname, $username, $password)
#dbh.do("update " + $tbl + " set name = 'new_data' where name = 'old_data';")

##### データ削除 #####
dbh = DBI.connect("dbi:mysql:" + $dbname + ":" + $hostname, $username, $password)
dbh.do("delete from " + $tbl + " where name = 'data';")

##### データ表示 #####
#dbh = DBI.connect("dbi:mysql:" + $dbname + ":" + $hostname, $username, $password)
#$sql = "select * from " + $tbl + ";"
dbh.select_all($sql) do |row|
printf "%s, %s, %s<br>\n", row[0], row[1], row[2]
end

rescue DBI::DatabaseError => e
p "Error code: #{ e.err }<br>"
p "Error message: #{ e.errstr }<br>"
ensure
dbh.disconnect if dbh
end

print "</body></html>\n";

●CGI(Ruby + MySQL、DBI:MySQL、require "mysql") / ruby_dbi2_mysql.rb

 テキストで表示させたい方はこちらです。
#!/usr/bin/ruby

require "mysql"

$hostname = "127.0.0.1"
$dbname = "データベース名"
$username = "ユーザ名"
$password = "パスワード"
$tbl = "テーブル名"

print "Content-type: text/html\n\n";
print "<html<>head<>title>CGI-Ruby DBI TEST</title>n";
print "<meta http-equiv='content-type' content='text/html; charset=utf-8'>\n";
print "</head<>body<>h2>DB接続テスト(CGI-Ruby GEM版)</h2>\n";

conn = Mysql::connect($hostname, $username, $password, $dbname)

# 文字コードをUTF8に設定
conn.query("set character set utf8")

##### データ挿入 #####
#conn.query("insert into " + $tbl + " (value1,value2,value3) values ('data1','data2','data3');")

##### データ更新 #####
#conn.query("update " + $tbl + " set name = 'new_data' where name = 'old_data';")

##### データ削除 #####
#conn.query("delete from " + $tbl + " where name = 'data';")

# DBに問い合わせ
rs = conn.query("SELECT * FROM " + $tbl)

# 検索結果を表示
rs.each do |r|
puts r.join ", "
print "<br />\n"
end

# コネクションを閉じる
conn.close

print "</body<>/html>\n";


●PHP / php.php
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>PHP TEST</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
</head>
<body>
<h2>PHPテスト</h2>
<?php
	print Date("y/m/d H:i:s");
?>
<hr>
<?php
	phpinfo();
?>
</body>
</html>

●PHP + PostgreSQL / php_postgres.php

 テキストで表示させたい方はこちらです。
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>PHP PostgreSQL TEST</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
</head>

<body>

<h2>DB接続テスト(PHP PostgreSQL版)</h2>

<?php
  $hostname = "localhost";
  $dbport = "5432";
  $username = "ユーザ名";
  $password = "パスワード";
  $dbname = "データベース名";
  $tbl = "テーブル名";

  //$connect = pg_connect("host=$hostname port=$dbport dbname=$dbname user=$username password=$password");
  $connect = pg_connect("dbname=$dbname user=$username");

  // データ挿入
  //$sql1 = "insert into $tbl values('data1,'data2','data3')";
  //$rs = pg_exec($sql1);

  // データ更新
  //$sql2 = "update $tbl set name='new_data' where name='old_data'";
  //$rs = pg_exec($sql2);

  // データ削除
  //$sql3 = "delete from $tbl where name='data'";
  //$rs = pg_exec($sql3);

  // データ表示
  $sql = "select * from $tbl";
  $rs = pg_exec($sql);
  $ct = pg_numrows($rs);

  for($i=0; $i<$ct;$i++){
    $item = pg_fetch_array($rs, $i);
    print "${item['row1']} / ";
    print "${item['row2']} / ";
    print "${item['row3']}<br>";
  }

  pg_close($connect);
?>

</body>
</html>

●PHP + MySQL / php_mysql.php

 テキストで表示させたい方はこちらです。
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>PHP MySQL TEST</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
</head>

<body>

<h2>DB接続テスト(PHP MySQL版)</h2>

<?php
  $hostname = "localhost";
  $username = "ユーザ名";
  $password = "パスワード";
  $dbname = "データベース名";
  $tbl = "テーブル名";

  $connect = mysql_connect($hostname, $username, $password);
  mysql_select_db($dbname);

  // データ挿入
  //$sql1 = "insert into $tbl values('data1','data2','data3')";
  //$sqlq1 = mysql_query($sql1, $connect);

  // データ更新
  //$sql2 = "update $tbl set name='new_data' where name='old_data'";
  //$sqlq2 = mysql_query($sql2, $connect);

  // データ削除
  //$sql3 = "delete from $tbl where name='data'";
  //$sqlq3 = mysql_query($sql3, $connect);

  // データ表示
  $sql = "select * from $tbl";
  $sqlq = mysql_query($sql, $connect);

  while($row = mysql_fetch_array($sqlq)){
    echo $row["row1"] . " / ";
    echo $row["row2"] . " / ";
    echo $row["row3"] . "<br>";
  }
  
  mysql_free_result($sqlq);
  mysql_close($connect);
?>

</body>
</html>

●J2SDK / test.java
public class test {
  public static void main(String[] args) {
    System.out.println("Hello World");
  }
}

●Java JSP / test.jsp

 このファイルは$CATALINA_HOME/webapps/ROOTに保存してください。
<%@ page
  language="java"
  contentType="text/html; charset=utf-8"
%>
<%
  String jpString = "こんにちは";
  String enString = "HELLO";
%>
<html>
<head>
<title>Java JSP TEST</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
</head>
<body>
<h2>Java JSPテスト</h2>
jpString : <%=jpString%>
<br>
enString : <%=enString%>
</body>
</html>

●Java JSP + PostgreSQL / java_postgres.jsp(CentOS 7及びFedora 22で動作しない)

 このファイルは$CATALINA_HOME/webapps/ROOTに保存してください。
 テキストで表示させたい方はこちらです。
<%@ page
  import="java.sql.*"
  language="java"
  contentType="text/html; charset=utf-8"
%>
<%
try {
  Class.forName("org.postgresql.Driver");
}
  catch(Exception e) {
System.out.println("<p>JDBCドライバロードエラー<br>" + e.toString() + "</p>");
  //Tomcat5.5で「System」を記載すると出力されない。
}
  String jdbcUrl = "jdbc:postgresql:データベース名?charSet=UTF8";
  String user = "ユーザ名";
  String password = "パスワード";

  Connection con = null;
  Statement st = null;
  ResultSet rs = null;
  String sql1 = ""; //データ挿入用
  String sql2 = ""; //データ更新用
  String sql3 = ""; //データ削除用
  String sql = ""; //データ表示用
  int cnt;
  String test = "";

  try{
    con = DriverManager.getConnection(jdbcUrl,user,password);
    st = con.createStatement();
    //sql = "set client_encoding='UTF8'";
    //st.execute(sql);

    ///// データ挿入
    //sql1 = "insert into テーブル名 values('data1','data2','data3')";
    //cnt = st.executeUpdate(sql1);

    ///// データ更新
    //sql2 = "update テーブル名 set name='new_data' where name='old_data'";
    //cnt = st.executeUpdate(sql2);

    ///// データ削除
    //sql3 = "delete from テーブル名 where name='data'";
    //cnt = st.executeUpdate(sql3);

    sql = "select * from テーブル名";
    rs = null;
    rs = st.executeQuery(sql);

    while(rs.next()){
      test += rs.getString("row1") + " / ";
      test += rs.getString("row2") + " / ";
      test += rs.getString("row3") + "<br>";
    }

  }catch(Exception e){
    System.out.println(e);
  //Tomcat5.5で「System」を記載すると出力されない。
  }finally{
      try{
        if(rs != null){
          rs.close();
        }
        if(st != null){
          st.close();
        }
        if(con != null){
          con.close();
        }
      }catch(Exception e){
      }
  }
%>

<html>
<head>
<title>Java JSP PostgreSQL TEST</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
</head>
</body>

<h2>DB接続テスト(Java JSP PostgreSQL版)</h2>

<%=test%>

</body>
</html>

●Java JSP + MySQL / java_mysql.jsp(CentOS 7及びFedora 22で動作しない)

 このファイルは$CATALINA_HOME/webapps/ROOTに保存してください。
 テキストで表示させたい方はこちらです。
<%@ page
  import="java.sql.*"
  language="java"
  contentType="text/html; charset=utf-8"
%>
<%
  Class.forName("com.mysql.jdbc.Driver");
  String jdbcUrl = "jdbc:mysql://localhost:3306/
    \データベース名?useUnicode=true&characterEncoding=UTF8";
  String user = "ユーザ名";
  String password = "パスワード";

  Connection con = null;
  Statement st = null;
  ResultSet rs = null;
  String sql1 = ""; //データ挿入用
  String sql2 = ""; //データ更新用
  String sql3 = ""; //データ削除用
  String sql = ""; //データ表示用
  int cnt;
  String test = "";

  try{
    con = DriverManager.getConnection(jdbcUrl,user,password);
    st = con.createStatement();
    //sql = "set client_encoding='UTF8'";
    //st.execute(sql);

    ///// データ挿入
    //sql1 = "insert into テーブル名 values('data1','data2','data3')";
    //cnt = st.executeUpdate(sql1);

    ///// データ更新
    //sql2 = "update テーブル名 set name='new_data' where name='old_data'";
    //cnt = st.executeUpdate(sql2);

    ///// データ削除
    //sql3 = "delete from テーブル名 where name='data'";
    //cnt = st.executeUpdate(sql3);

    sql = "select * from テーブル名";
    rs = null;
    rs = st.executeQuery(sql);

    while(rs.next()){
      test += rs.getString("name") + " / ";
      test += rs.getString("telno") + " / ";
      test += rs.getString("email") + "<br>";
    }

  }catch(Exception e){
    System.out.println(e);
  }finally{
      try{
        if(rs != null){
          rs.close();
        }
        if(st != null){
          st.close();
        }
        if(con != null){
          con.close();
        }
      }catch(Exception e){
      }
  }
%>

<html>
<head>
<title>Java JSP MySQL TEST</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
</head>
</body>

<h2>DB接続テスト(Java JSP MySQL版)</h2>

<%=test%>

</body>
</html>

●Java Servlet / JavaServlet.java

 $CATALINA_HOME/webapps/JavaServletを作成します。
 JavaServletディレクトリにJavaServlet.javaを保存します。また、WEB-INFディレクトリを作成します。
 classes及びlibディレクトリを作成します。
 classesディレクトリにJavaServlet.javaをコンパイルして生成されたJavaServlet.classを保存します。
 WEB-INFディレクトリにJavaServlet用のweb.xmlを作成します。
 詳細については、こちらを参照してください。

 CentOS5.6の環境(tomcat5-5.5.23-0jpp.17.el5_6、tomcat5-servlet-2.4-api-5.5.23-0jpp.17.el5_6)でコンパイルすると下記のようなエラーが表示されます。
 なお、Fedora14の環境(tomcat6-6.0.26-16.fc14.noarch、tomcat6-servlet-2.5-api-6.0.26-16.fc14.noarch)では、そのままで問題なく動作します。
The serializable class ******** does not declare
           a static final serialVersionUID field of type long
 このため、public class ***** extends HttpServlet { のすぐ下に、
private static final long serialVersionUID = 1L;
を追加後、再コンパイルしてください。

 テキストで表示させたい方はこちらです。
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class クラス名 extends HttpServlet {

  public void init() throws ServletException
  {
  }

  //HTTP Get リクエストの処理
  public void doGet(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException
  {
    response.setContentType("text/html; charset=utf-8");
    PrintWriter out = response.getWriter();

    String jpString = "こんにちは";
    String enString = "HELLO";

    out.println("<html><head><title>JavaServlet TEST</title>");
    out.println("<meta http-equiv='content-type' content='text/html; charset=utf-8'>");
    out.println("</head><body>");
    out.println("<h2>JavaServletテスト</h2>");
    out.println("jpString : " + jpString);
    out.println("<br>");
    out.println("enString : " + enString);
    out.println("</body></html>");
    out.close();
  }

  //HTTP Post リクエストの処理
  public void doPost(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException
  {
    doGet(request, response);
  }
}

●Java Servlet + PostgreSQL / JavaServletPostgres.java

 $CATALINA_HOME/webapps/JavaServletPostgresを作成します。
 JavaServletPostgresディレクトリにJavaServletPostgres.javaを保存します。また、WEB-INFディレクトリを作成します。
 classes及びlibディレクトリを作成します。
 classesディレクトリにJavaServletPostgres.javaをコンパイルして生成されたJavaServletPostgres.classを保存します。
 WEB-INFディレクトリにJavaServletPostgres用のweb.xmlを作成します。
 詳細については、こちらを参照してください。

 CentOS5.6の環境(tomcat5-5.5.23-0jpp.17.el5_6、tomcat5-servlet-2.4-api-5.5.23-0jpp.17.el5_6)でコンパイルすると下記のようなエラーが表示されます。
 なお、Fedora14の環境(tomcat6-6.0.26-16.fc14.noarch、tomcat6-servlet-2.5-api-6.0.26-16.fc14.noarch)では、そのままで問題なく動作します。
The serializable class ******** does not declare
           a static final serialVersionUID field of type long
 このため、public class ***** extends HttpServlet { のすぐ下に、
private static final long serialVersionUID = 1L;
を追加後、再コンパイルしてください。

 CentoOS5.6環境用及びチェック項目追加版を記載しました。
 テキストで表示させたい方はこちらです。
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;

public class クラス名 extends HttpServlet {

  public void init() throws ServletException
  {
  }

  //HTTP Get リクエストの処理
  public void doGet(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException
  {
    response.setContentType("text/html; charset=utf-8");
    PrintWriter out = response.getWriter();

    Connection con = null;
    String jdbcUrl = "jdbc:postgresql:データベース名?charSet=UTF8";
    String user = "ユーザ名";
    String password = "パスワード";

    try{
      Class.forName("org.postgresql.Driver");
      con = DriverManager.getConnection(jdbcUrl,user,password);
    }catch(ClassNotFoundException e){
    }catch(SQLException e){
    }

    Statement st = null;
    ResultSet rs = null;
    String sql1 = ""; //データ挿入用
    String sql2 = ""; //データ更新用
    String sql3 = ""; //データ削除用
    String sql = ""; //データ表示用
    int cnt;
    String test = "";

    try{
    con = DriverManager.getConnection(jdbcUrl,user,password);
    st = con.createStatement();
    //sql = "set client_encoding='UTF8'";
    //st.execute(sql);

    ///// データ挿入
    //sql1 = "insert into テーブル名 values('data1','data2','data3')";
    //cnt = st.executeUpdate(sql1);

    ///// データ更新
    //sql2 = "update テーブル名 set name='new_data' where name='old_data'";
    //cnt = st.executeUpdate(sql2);

    ///// データ削除
    //sql3 = "delete from テーブル名 where name='data'";
    //cnt = st.executeUpdate(sql3);

    sql = "select * from テーブル名";
    rs = null;
    rs = st.executeQuery(sql);

    while(rs.next()){
      test += rs.getString("row1") + " / ";
      test += rs.getString("row2") + " / ";
      test += rs.getString("row3") + "<br>";
    }

    }catch(Exception e){
      System.out.println(e);
    }finally{
      try{
        if(rs != null){
          rs.close();
        }
        if(st != null){
          st.close();
        }
        if(con != null){
          con.close();
        }
      }catch(Exception e){
      }
    }

    out.println("<html><head><title>JavaServlet PostgreSQL TEST</title>");
    out.println("<meta http-equiv='content-type' content='text/html; charset=utf-8'>");
    out.println("</head><body>");
    out.println("<h2>DB接続テスト(JavaServlet PostgreSQL版)</h2>");
    out.println(test);
    out.println("</body></html>");
    out.close();
  }

  //HTTP Post リクエストの処理
  public void doPost(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException
  {
    doGet(request, response);
  }
}

 CentoOS5.6環境用及びチェック項目追加版(2011.06.08)

 テキストで表示させたい方はこちらです。
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
//import java.net.*;
import java.sql.*;

public class クラス名 extends HttpServlet {
  private static final long serialVersionUID = 1L;

  //HTTP Get リクエストの処理
  public void doGet(HttpServletRequest request, HttpServletResponse response)
  throws IOException, ServletException {

    String drv = "org.postgresql.Driver";
    String jdbcUrl = "jdbc:postgresql://localhost:5432/データベース名?useUnicode=true&characterEncoding=UTF8";

    ///// データ挿入用
    //String sql1 = "insert into テーブル名 values('S.Suzuki','123-4567-8989','s-suzu@gmail.jp')";
    ///// データ更新用
    //String sql2 = "update テーブル名 set name='佐藤さん' where name='S.Suzuki'";
    ///// データ削除用
    //String sql3 = "delete from テーブル名 where name='佐藤さん'";
    ///// データ表示用
    String sql = "select * from テーブル名";

    String test = "";

    String user = "ユーザ名";
    String password = "パスワード";
    Connection cn = null;
    Statement st = null;
    ResultSet rs = null;

    // コンテンツタイプ指定
    response.setContentType("text/html; charset=utf-8");

    // HTMLヘッダ出力
    PrintWriter out = response.getWriter();
    out.println("<html><head><title>JavaServlet PostgreSQL TEST</title>");
    out.println("<meta http-equiv='content-type' content='text/html; charset=utf-8'>");
    out.println("</head><body>");
    out.println("<h2>DB接続テスト(JavaServlet PostgreSQL版)</h2>");

    // PostgreSQL JDBCドライバロード
    try {
      Class.forName(drv);
        out.println("ドライバのロードに成功しました<br />");
    } catch (Exception e) {
        out.println("<font color=\"red\">JDBDドライバーロードエラー</font><br />" + e.toString() + "<br /><br />");
    }

    // PosggreSQL JDBC接続
    try {
      cn = DriverManager.getConnection(jdbcUrl,user,password);
        out.println("データベースの接続に成功しました<br /><br />");
    } catch (Exception e) {
        out.println("<font color=\"red\">データベースの接続に失敗しました</font><br />");
        out.println("<font color=\"red\">データベース名、接続ユーザ名、パスワードを確認してください</font><br />" + e.toString()+ "<br /><br />");
    }

    // オートコミット解除
    try {
      cn.setAutoCommit(false);
    } catch (Exception e) {
      out.println("<font color=\"red\">オートコミット解除エラー</font><br />" + e.toString()+ "<br /><br />");
    }

    // PostgreSQL JDBC問い合わせ SQL作成
    try {
      st = cn.createStatement();
    } catch (Exception e) {
        out.println("<font color=\"red\">JDBC 問い合わせ SQL 作成エラー</font><br />" + e.toString() + "<br /><br />");
    }

    // PostgreSQL JDBC レコード追加
    try {
//      レコード追加・更新・削除により「sql*」を書き換える。
//      int cnt = st.executeUpdate(sql2);
      cn.commit();
    } catch (Exception e) {
      out.println("<font color=\"red\">JDBC レコード追加エラー</font><br />" + e.toString() + "<br /><br />");
    }

    // PostgreSQL JDBCレコードセットオープン
    try {
      rs = st.executeQuery(sql);
    } catch (Exception e) {
        out.println("<font color=\"red\">JDBC レコードセットオープンエラー</font><br />" + e.toString() + "<br /><br />");
    }

    // PostgreSQL JDBCレコードセットリード
    try {
      while(rs.next()){
        test += rs.getString("name") + " / ";
        test += rs.getString("telno") + " / ";
        test += rs.getString("email") + "<br />";
      }
      out.println(test);
    } catch (Exception e) {
        out.println("<font color=\"red\">JDBC レコードセットリードエラー</font><br />" + e.toString() + "<br /><br />");
    }

    // PostgreSQL JDBCレコードセットクローズ
    try {
      rs.close();
    } catch (Exception e) {}

    // PostgreSQL JDBCステートメントクローズ
    try {
      st.close();
    } catch (Exception e) {}

    // PostgreSQL JDBC接続クローズ
    try {
      cn.close();
        out.println("<br />データベースの切断に成功しました<br />");
    } catch (Exception e) {
        out.println("<font color=\"red\">データベースの切断に失敗しました</font><br />");
    }

    // HTML テイル出力
    out.println("</body></html>");
    out.close();

  }

}

●Java Servlet + MySQL / JavaServletMysql.java

 $CATALINA_HOME/webapps/JavaServletMysqlを作成します。
 JavaServletMysqlディレクトリにJavaServletMysql.javaを保存します。また、WEB-INFディレクトリを作成します。
 classes及びlibディレクトリを作成します。
 classesディレクトリにJavaServletMysql.javaをコンパイルして生成されたJavaServletMysql.classを保存します。
 WEB-INFディレクトリにJavaServletMysql用のweb.xmlを作成します。
 詳細については、こちらを参照してください。

 CentOS5.6の環境(tomcat5-5.5.23-0jpp.17.el5_6、tomcat5-servlet-2.4-api-5.5.23-0jpp.17.el5_6)でコンパイルすると下記のようなエラーが表示されます。
 なお、Fedora14の環境(tomcat6-6.0.26-16.fc14.noarch、tomcat6-servlet-2.5-api-6.0.26-16.fc14.noarch)では、そのままで問題なく動作します。
The serializable class ******** does not declare
           a static final serialVersionUID field of type long
 このため、public class ***** extends HttpServlet { のすぐ下に、
private static final long serialVersionUID = 1L;
を追加後、再コンパイルしてください。
 CentoOS5.6環境用及びチェック項目追加版を記載しました。

 テキストで表示させたい方はこちらです。
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;

public class クラス名 extends HttpServlet {

  public void init() throws ServletException
  {
  }

  //HTTP Get リクエストの処理
  public void doGet(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException
  {
    response.setContentType("text/html; charset=utf-8");
    PrintWriter out = response.getWriter();

    Connection con = null;
    String jdbcUrl = "jdbc:mysql://localhost:3306/データベース名?useUnicode=true&characterEncoding=UTF8";
    String user = "ユーザ名";
    String password = "パスワード";

    try{
      Class.forName("com.mysql.jdbc.Driver");
      con = DriverManager.getConnection(jdbcUrl,user,password);
    }catch(ClassNotFoundException e){
    }catch(SQLException e){
    }

    Statement st = null;
    ResultSet rs = null;
    String sql1 = ""; //データ挿入用
    String sql2 = ""; //データ更新用
    String sql3 = ""; //データ削除用
    String sql = ""; //データ表示用
    int cnt;
    String test = "";

    try{
      st = con.createStatement();
    ///// データ挿入
    //sql1 = "insert into テーブル名 values('data1','data2','data3')";
    //cnt = st.executeUpdate(sql1);

    ///// データ更新
    //sql2 = "update テーブル名 set name='new_data' where name='old_data'";
    //cnt = st.executeUpdate(sql2);

    ///// データ削除
    //sql3 = "delete from テーブル名 where name='data'";
    //cnt = st.executeUpdate(sql3);

    sql = "select * from テーブル名";
    rs = null;
    rs = st.executeQuery(sql);

    while(rs.next()){
      test += rs.getString("name") + " / ";
      test += rs.getString("telno") + " / ";
      test += rs.getString("email") + "<br />";
    }

    }catch(Exception e){
      System.out.println(e);
    }finally{
      try{
        if(rs != null){
          rs.close();
        }
        if(st != null){
          st.close();
        }
        if(con != null){
          con.close();
        }
      }catch(Exception e){
      }
    }

    out.println("<html><head><title>JavaServlet MySQL TEST</title>");
    out.println("<meta http-equiv='content-type' content='text/html; charset=utf-8'>");
    out.println("</head><body>");
    out.println("<h2>DB接続テスト(JavaServlet MySQL版)</h2>");
    out.println(test);
    out.println("</body></html>");
    out.close();
  }

  //HTTP Post リクエストの処理
  public void doPost(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException
  {
    doGet(request, response);
  }
}

 CentoOS5.6環境用及びチェック項目追加版(2011.06.08)

 テキストで表示させたい方はこちらです。
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
//import java.net.*;
import java.sql.*;

public class クラス名 extends HttpServlet {
  private static final long serialVersionUID = 1L;

  //HTTP Get リクエストの処理
  public void doGet(HttpServletRequest request, HttpServletResponse response)
  throws IOException, ServletException {

    String drv = "com.mysql.jdbc.Driver";
    String jdbcUrl = "jdbc:mysql://localhost:3306/データベース名?useUnicode=true&characterEncoding=UTF8";

    ///// データ挿入用
    //String sql1 = "insert into テーブル名 values('S.Suzuki','123-4567-8989','s-suzu@gmail.jp')";
    ///// データ更新用
    //String sql2 = "update テーブル名 set name='佐藤さん' where name='S.Suzuki'";
    ///// データ削除用
    //String sql3 = "delete from テーブル名 where name='佐藤さん'";
    ///// データ表示用
    String sql = "select * from テーブル名";

    String test = "";

    String user = "ユーザ名";
    String password = "パスワード";
    Connection cn = null;
    Statement st = null;
    ResultSet rs = null;

    // コンテンツタイプ指定
    response.setContentType("text/html; charset=utf-8");

    // HTMLヘッダー出力
    PrintWriter out = response.getWriter();
    out.println("<html><head><title>JavaServlet MySQL TEST</title>");
    out.println("<meta http-equiv='content-type' content='text/html; charset=utf-8'>");
    out.println("</head><body>");
    out.println("<h2>DB接続テスト(JavaServlet MySQL版)</h2>");

    // MySQL JDBCドライバロード
    try {
      Class.forName(drv);
        out.println("ドライバのロードに成功しました<br />");
    } catch (Exception e) {
        out.println("<font color=\"red\">JDBDドライバーロードエラー</font><br />" + e.toString() + "<br /><br />");
    }

    // MySQL JDBC接続
    try {
      cn = DriverManager.getConnection(jdbcUrl,user,password);
        out.println("データベースの接続に成功しました<br /><br />");
    } catch (Exception e) {
        out.println("<font color=\"red\">データベースの接続に失敗しました</font><br />");
        out.println("<font color=\"red\">データベース名、接続ユーザ名、パスワードを確認してください</font><br />" + e.toString()+ "<br /><br />");
    }

    // オートコミット解除
    try {
      cn.setAutoCommit(false);
    } catch (Exception e) {
      out.println("<font color=\"red\">オートコミット解除エラー</font><br />" + e.toString()+ "<br /><br />");
    }

    // MySQL JDBC問い合わせ SQL作成
    try {
      st = cn.createStatement();
    } catch (Exception e) {
        out.println("<font color=\"red\">JDBC 問い合わせ SQL 作成エラー</font><br />" + e.toString() + "<br /><br />");
    }

    // MySQL JDBC レコード追加・更新・削除
//    try {
//      レコード追加・更新・削除により「sql*」を書き換える。
//      int cnt = st.executeUpdate(sql2);
//      cn.commit();
//    } catch (Exception e) {
//      out.println("<font color=\"red\">JDBC レコード追加エラー</font><br />" + e.toString() + "<br /><br />")
//    }

    // MySQL JDBCレコードセットオープン
    try {
      rs = st.executeQuery(sql);
    } catch (Exception e) {
        out.println("<font color=\"red\">JDBC レコードセットオープンエラー</font><br />" + e.toString() + "<br /><br />");
    }

    // MySQL JDBCレコードセットリード
    try {
      while(rs.next()){
        test += rs.getString("name") + " / ";
        test += rs.getString("telno") + " / ";
        test += rs.getString("email") + "<br />";
      }
      out.println(test);
    } catch (Exception e) {
        out.println("<font color=\"red\">JDBC レコードセットリードエラー</font><br />" + e.toString() + "<br /><br />");
    }

    // MySQL JDBCレコードセットクローズ
    try {
      rs.close();
    } catch (Exception e) {}

    // MySQL JDBCステートメントクローズ
    try {
      st.close();
    } catch (Exception e) {}

    // MySQL JDBC接続クローズ
    try {
      cn.close();
        out.println("<br />データベースの切断に成功しました<br />");
    } catch (Exception e) {
        out.println("<font color=\"red\">データベースの切断に失敗しました</font><br />");
    }

    // HTML フッター出力
    out.println("</body></html>");
    out.close();

  }

}