解答例 - 実習課題1 - 2.SQL文の実行
(実習課題1)
1章の実習課題1のプログラムを改良しなさい。
- ウィンドウに「更新」ボタンを追加する事。
- テーブルの各セルは編集可能な状態にし、「更新」ボタンを押すと、各セルを編集した結果がデータベースに反映されるようにする事。
- 編集した行に関するSQL文を発行するように工夫する事。
- トランザクション処理は考慮しなくて良い。
解答例
▼データベースアクセス用クラスのソース
package com.techscore.jdbc.chapter2.exercise1;
/**
* CoonectDataBase.java
* TECHSCORE JDBC2章 実習課題1
*
* Copyright (c) 2004 Four-Dimensional Data, Inc.
*/
import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.DriverManager;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
public class ProductDAO{
private Connection getConnection() throws SQLException,ClassNotFoundException{
Connection conn = null;
Class.forName("org.postgresql.Driver");
conn = DriverManager.getConnection("jdbc:postgresql://dbserver:5432/Training"
,"postgres" //ユーザ名
,""); //パスワード
return conn;
}
public List loadSummary() throws SQLException,ClassNotFoundException{
List list = new LinkedList();
Connection conn = null;
try{
conn = getConnection();
final String sql = "select p_num, p_name, type, price" +
" from product order by p_num";
Statement statement = conn.createStatement();
ResultSet result = statement.executeQuery(sql);
while (result.next()){
Product data = new Product(
result.getInt(1),
result.getString(2),
result.getString(3),
result.getInt(4));
list.add(data);
}
result.close();
statement.close();
}finally{
if (conn != null){
conn.close();
}
}
return list;
}
public void update(List list) throws SQLException,ClassNotFoundException{
Connection conn = null;
try{
conn = getConnection();
Statement statement = null;
Iterator ite=list.iterator();
for(int i=0; ite.hasNext(); i++){
Product product = (Product)ite.next();
final String sql = "update product set" +
" p_name = \'" + product.getPName() + "\'" +
",type = \'" + product.getType() + "\'" +
",price = " + product.getPrice() +
" where p_num = " + product.getPNum();
statement = conn.createStatement();
statement.executeUpdate(sql);
statement.close();
}
}finally{
if (conn != null){
conn.close();
}
}
}
}
▼Product(製品)情報管理クラスのソース
▼テーブル表示ウィンドウ作成クラスのソース
package com.techscore.jdbc.chapter2.exercise1;
/**
* DisplayProductTable.java
* TECHSCORE JDBC2章 実習課題1
*
* Copyright (c) 2004 Four-Dimensional Data, Inc.
*/
import java.util.Iterator;
import java.util.List;
import java.util.LinkedList;
import java.sql.SQLException;
import javax.swing.AbstractButton;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class DisplayProductTable extends JPanel implements ActionListener {
private JTable table = null;
private List list = null;
private Object[][] originalData;
public DisplayProductTable() {
super(new GridLayout(2,1));
ProductDAO productDAO = new ProductDAO();
try{
list = (List)productDAO.loadSummary();
//テーブルデータ内容
Object[][] data = new Object[list.size()][4];
originalData = new Object[list.size()][4];
Iterator ite=list.iterator();
for(int i=0; ite.hasNext(); i++){
Product product = (Product)ite.next();
data[i][0] = new Integer(product.getPNum()).toString();
data[i][1] = product.getPName();
data[i][2] = product.getType();
data[i][3] = new Integer(product.getPrice()).toString();
originalData[i][0] = new Integer(product.getPNum()).toString();
originalData[i][1] = product.getPName();
originalData[i][2] = product.getType();
originalData[i][3] = new Integer(product.getPrice()).toString();
}
createParts(data);
}catch(SQLException e){
e.printStackTrace();
System.exit(1);
}catch(ClassNotFoundException e){
e.printStackTrace();
System.exit(1);
}
}
private void createParts(Object[][] data){
//テーブルのタイトル
String[] columnNames = {"製品ナンバー",
"製品名",
"製品のタイプ",
"製品の価格"};
table = new JTable(data, columnNames);
table.setPreferredScrollableViewportSize(new Dimension(400, 100));
JScrollPane scrollPane = new JScrollPane(table);
add(scrollPane);
JButton bu = new JButton("更新");
bu.setVerticalTextPosition(AbstractButton.BOTTOM);
bu.setHorizontalTextPosition(AbstractButton.CENTER);
bu.setActionCommand("update");
bu.setSize(20,20);
bu.addActionListener(this);
JPanel panel = new JPanel();
panel.setSize(10,30);
panel.add(bu);
add(panel);
}
public void actionPerformed(ActionEvent e) {
if ("update".equals(e.getActionCommand())) {
ProductDAO product = new ProductDAO();
System.out.println("Push Update Button");
List list = (List)checkUpdateData();
try{
product.update(list);
}catch(SQLException ex){
ex.printStackTrace();
System.exit(1);
}catch(ClassNotFoundException ex){
ex.printStackTrace();
System.exit(1);
}
}
//createAndShowGUI(); //再表示
}
private List checkUpdateData(){
int numRows = table.getRowCount();
int numCols = table.getColumnCount();
List list = new LinkedList();
javax.swing.table.TableModel model = table.getModel();
System.out.println("check of data: ");
for (int i=0; i < numRows; i++) {
System.out.print(" row " + i + ":");
for (int j=1; j < numCols; j++) {
System.out.print(" " + model.getValueAt(i, j));
if (!(model.getValueAt(i,j).equals(originalData[i][j]))){
Product product = new Product();
product.setPNum(Integer.parseInt((String)model.getValueAt(i,0)));
product.setPName((String)model.getValueAt(i,1));
product.setType((String)model.getValueAt(i,2));
product.setPrice(Integer.parseInt((String)model.getValueAt(i,3)));
//更新前データを保存
originalData[i][1] = (String)model.getValueAt(i,1);
originalData[i][2] = (String)model.getValueAt(i,2);
originalData[i][3] = (String)model.getValueAt(i,3);
list.add(product);
System.out.println("[UP]");
break;
}
}
System.out.println();
}
System.out.println("--------------------------");
return list;
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("製品情報テーブル表示");
DisplayProductTable newContentPane = new DisplayProductTable();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(newContentPane);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
▼データベースの指定

