解答例 - 実習課題3 - 4.ラージオブジェクト
(実習課題3)
以下のプログラムを作成しなさい。
- 「product_introduction」にホームページデータを格納するコンソールプログラム。
- プログラムの引数は1番目が製品番号、2番目がHTMLファイル。
- 保存対象は1枚のHTMLファイルだけでよい。
- 保存される文字コードはEUCになるようにすること。
解答例
▼データベースアクセス用クラスのソース
package com.techscore.jdbc.chapter4.exercise3;
/**
* ProductIntroductionDAO.java
* TECHSCORE JDBC4章 実習課題3
*
* Copyright (c) 2004 Four-Dimensional Data, Inc.
*/
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.DriverManager;
import java.io.StringReader;
public class ProductIntroductionDAO{
private PreparedStatement statement = null;
private Connection conn = null;
private Connection getConnection() throws SQLException,ClassNotFoundException{
Class.forName("org.postgresql.Driver");
conn = DriverManager.getConnection("jdbc:postgresql://dbserver:5432/Training"
,"postgres" //ユーザ名
,""); //パスワード
conn.setAutoCommit(false); //自動コミットモード解除
return conn;
}
public void insertImage(int pNum,StringReader sr, int length) throws SQLException,ClassNotFoundException{
conn = getConnection();
final String sql = "insert into product_introduction values(?,?)";
statement = conn.prepareStatement(sql);
statement.setInt(1,pNum);
statement.setCharacterStream(2, sr, length);
statement.executeUpdate();
conn.commit();
}
public void finishTransaction() throws SQLException{
try{
statement.close();
}finally{
if (conn != null){
conn.close();
}
}
}
}
▼データ挿入測定クラスのソース
package com.techscore.jdbc.chapter4.exercise3;
/**
* InsertHtmlFile.java
* TECHSCORE JDBC4章 実習課題3
*
* Copyright (c) 2004 Four-Dimensional Data, Inc.
*/
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.StringReader;
import java.sql.SQLException;
public class InsertHtmlFile {
public static void main(String[] args) {
try {
ProductIntroductionDAO introductionDAO = new ProductIntroductionDAO();
int pNum =Integer.parseInt(args[0]);
String fileName = args[1];
System.out.println("■開始!");
File file = new File(fileName);
FileInputStream input = new FileInputStream(file);
BufferedReader bReader =
new BufferedReader(
new InputStreamReader(input, "EUC-JP"));
String line = null;
StringBuffer tmp = new StringBuffer();
while ((line = bReader.readLine()) != null) {
tmp.append(line);
}
StringReader reader=new StringReader(tmp.toString());
introductionDAO.insertImage(pNum,reader,(int)tmp.length());
input.close();
introductionDAO.finishTransaction();
System.out.println("■終了!");
}catch(SQLException e){
e.printStackTrace();
}catch(ClassNotFoundException e){
e.printStackTrace();
}catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Usage:java InsertHtmlFile [製品番号] [HTMLファイル名]");
}catch(FileNotFoundException e){
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
}
}
▼データベースの指定

