3 Commits

Author SHA1 Message Date
bbc4fbd353 1030自主学習 2026-10-30 17:49:14 +09:00
bae6f62ca2 20261029 5段階目まで完了 2026-10-29 15:56:21 +09:00
9f7fa737ef 20261028 JavaSQL演習 2026-10-28 16:58:01 +09:00
7 changed files with 291 additions and 221 deletions

View File

@@ -1,10 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<classpath> <classpath>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"> <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
<attributes>
<attribute name="module" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="src" path="src"/> <classpathentry kind="src" path="src"/>
<classpathentry kind="lib" path="lib/mysql-connector-java-8.0.23.jar"/> <classpathentry kind="lib" path="lib/mysql-connector-java-8.0.23.jar"/>
<classpathentry kind="lib" path="実行例/DAO_Simple.jar"/> <classpathentry kind="lib" path="実行例/DAO_Simple.jar"/>

View File

@@ -6,18 +6,18 @@
</projects> </projects>
<buildSpec> <buildSpec>
<buildCommand> <buildCommand>
<name>org.eclipse.wst.validation.validationbuilder</name> <name>org.eclipse.jdt.core.javabuilder</name>
<arguments> <arguments>
</arguments> </arguments>
</buildCommand> </buildCommand>
<buildCommand> <buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name> <name>org.eclipse.wst.validation.validationbuilder</name>
<arguments> <arguments>
</arguments> </arguments>
</buildCommand> </buildCommand>
</buildSpec> </buildSpec>
<natures> <natures>
<nature>org.eclipse.jdt.core.javanature</nature>
<nature>org.eclipse.wst.jsdt.core.jsNature</nature> <nature>org.eclipse.wst.jsdt.core.jsNature</nature>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures> </natures>
</projectDescription> </projectDescription>

View File

@@ -37,3 +37,4 @@ INSERT INTO department (nm_department) VALUES ('経理部');
INSERT INTO department (nm_department) VALUES ('システム開発事業部'); INSERT INTO department (nm_department) VALUES ('システム開発事業部');
INSERT INTO department (nm_department) VALUES ('教育事業部'); INSERT INTO department (nm_department) VALUES ('教育事業部');
INSERT INTO department (nm_department) VALUES ('営業企画部'); INSERT INTO department (nm_department) VALUES ('営業企画部');

View File

@@ -7,25 +7,30 @@
package com.rhizome.example.dao; package com.rhizome.example.dao;
import java.sql.Connection; import java.sql.Connection;
import java.sql.DriverManager; import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import com.rhizome.example.dto.EmployeeDTO; import com.rhizome.example.dto.EmployeeDTO;
//import com.rhizome.example.main.EmployeeDTO; import com.rhizome.example.util.DbUtil;
//実行結果をDTOに格納し、リストに追加
public class EmployeeDAO { public class EmployeeDAO {
private static final String TBL_NAME = "employee";
private static final String ID_EMPLOYEE = "id_employee";
private static final String NM_EMPLOYEE = "nm_employee";
private static final String KN_EMPLOYEE = "kn_employee";
private static final String MAIL_ADDRESS = "mail_address";
private static final String PASSWORD = "password";
private static final String ID_DEPARTMENT = "id_department";
/** DBコネクション */ /** DBコネクション */
//public Connection con; public Connection con;
/** DBステートメント */ /** DBステートメント */
//PreparedStatement stmt; PreparedStatement stmt;
/** 検索結果 */ /** 検索結果 */
//ResultSet rs; ResultSet rs;
/** /**
* インスタンス生成時DBコネクション * インスタンス生成時DBコネクション
@@ -33,9 +38,9 @@ public class EmployeeDAO {
* @throws ClassNotFoundException * @throws ClassNotFoundException
* @throws SQLException * @throws SQLException
*/ */
//public EmployeeDAO(Connection con) { public EmployeeDAO(Connection con) {
//this.con = con; this.con = con;
//} }
/** /**
* 社員テーブルの情報を全件取得する * 社員テーブルの情報を全件取得する
@@ -46,116 +51,140 @@ public class EmployeeDAO {
*/ */
public List<EmployeeDTO> selectAll() throws SQLException, ClassNotFoundException { public List<EmployeeDTO> selectAll() throws SQLException, ClassNotFoundException {
List<EmployeeDTO> rtnList = new ArrayList<>(); List<EmployeeDTO> rtnList = new ArrayList<>();
StringBuilder sql = new StringBuilder();
Connection con = null; sql.append(" SELECT ");
Statement stmt = null; sql.append(" " + "*");
sql.append(" FROM ");
sql.append(" " + TBL_NAME);
try { try {
// JDBCドライバの読み込み
Class.forName("com.mysql.cj.jdbc.Driver");
// Connectionの生成 this.stmt = con.prepareStatement(sql.toString());
con = DriverManager.getConnection( rs = stmt.executeQuery();
"jdbc:mysql://127.0.0.1:3306/rezodb", // データベース
"rezouser", // ユーザ名
"Rezo_0000" // パスワード
);
String sql = "SELECT * FROM employee";
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql);
// 実行結果をDTOに格納し、リストに追加
while (rs.next()) { while (rs.next()) {
EmployeeDTO emp = new EmployeeDTO(); EmployeeDTO emp = new EmployeeDTO();
emp.setId(rs.getInt("id_employee"));
emp.setId_employee(rs.getInt("id_employee")); emp.setName(rs.getString("nm_employee"));
emp.setNm_employee(rs.getString("nm_employee")); emp.setKana(rs.getString("kn_employee"));
emp.setKn_employee(rs.getString("kn_employee")); emp.setEmail(rs.getString("mail_address"));
emp.setMail_address(rs.getString("mail_address")); emp.setPass(rs.getString("password"));
emp.setPassword(rs.getString("password")); emp.setIdDep(rs.getInt("id_department"));
emp.setId_department(rs.getInt("id_department"));
rtnList.add(emp);
rtnList.add(emp);
} }
} finally {
} catch (ClassNotFoundException | SQLException e) { DbUtil.closeStatement(this.stmt);
e.printStackTrace(); }
} finally { return rtnList;
// Statement、Connectionの切断 }
try {
if (stmt != null) stmt.close(); //指定されたIDの社員データを取得する
if (con != null) con.close(); public List<EmployeeDTO> selectById(int id_employee)throws SQLException, ClassNotFoundException{
} catch (SQLException e) { List<EmployeeDTO> rtnList = new ArrayList<>();
e.printStackTrace(); StringBuilder sql = new StringBuilder();
} sql.append(" SELECT ");
} sql.append(" " + "*");
sql.append(" FROM ");
sql.append(" " + TBL_NAME);
sql.append(" WHERE ");
sql.append(" ID_EMPLOYEE = ?");
try {
this.stmt = con.prepareStatement(sql.toString());
this.stmt.setInt(1,id_employee );
rs = stmt.executeQuery();
while (rs.next()) {
EmployeeDTO emp = new EmployeeDTO();
emp.setId(rs.getInt("id_employee"));
emp.setName(rs.getString("nm_employee"));
emp.setKana(rs.getString("kn_employee"));
emp.setEmail(rs.getString("mail_address"));
emp.setPass(rs.getString("password"));
emp.setIdDep(rs.getInt("id_department"));
rtnList.add(emp);
}
}finally {
DbUtil.closeStatement(this.stmt);
}
return rtnList; return rtnList;
} }
//IDによる条件検索 //指定された社員のデータを削除する
public java.util.List<EmployeeDTO> selectById​(int id) throws SQLException, ClassNotFoundException, NumberFormatException{ public void empDelete(int id_employee)throws SQLException, ClassNotFoundException{
List<EmployeeDTO> rtnList = new ArrayList<>(); //SQL文の作成
StringBuilder sql = new StringBuilder();
Connection con = null; sql.append(" DELETE ");
Statement stmt = null; sql.append(" ");
sql.append(" FROM ");
try { sql.append(" " + TBL_NAME);
// JDBCドライバの読み込み sql.append(" WHERE ");
Class.forName("com.mysql.cj.jdbc.Driver"); sql.append(" ID_EMPLOYEE = ?");
// Connectionの生成
con = DriverManager.getConnection(
"jdbc:mysql://127.0.0.1:3306/rezodb", // データベース
"rezouser", // ユーザ名
"Rezo_0000" // パスワード
);
String sql = "SELECT id_employee FROM employee WHERE id_employee";
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql);
// 実行結果をDTOに格納し、リストに追加
while (rs.next()) {
EmployeeDTO emp = new EmployeeDTO();
emp.setId_employee(rs.getInt("id_employee"));
emp.setNm_employee(rs.getString("nm_employee"));
emp.setKn_employee(rs.getString("kn_employee"));
emp.setMail_address(rs.getString("mail_address"));
emp.setPassword(rs.getString("password"));
emp.setId_department(rs.getInt("id_department"));
rtnList.add(emp);
}
List<EmployeeDTO> selectList = new ArrayList<>();
for (EmployeeDTO employee : rtnList) {
if (employee.getPrimaryKeyValue().equals(id)) {
selectList.add(employee);
}
}
return selectList;
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
} finally {
// Statement、Connectionの切断
try {
if (stmt != null) stmt.close();
if (con != null) con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return rtnList;
}
try {
//SQL文の組み立て結果を保存
this.stmt = con.prepareStatement(sql.toString());
//?に代入
this.stmt.setInt(1,id_employee );
//削除命令
stmt.executeUpdate();
}finally {
DbUtil.closeStatement(this.stmt);
} }
}
public void empInsert(String name, String kana, String email,
String password, Integer idDep)throws SQLException, ClassNotFoundException{
StringBuilder sql = new StringBuilder();
sql.append(" INSERT ");
sql.append(" " + " INTO ");
sql.append(" " + TBL_NAME);
sql.append(" ( ");
sql.append(" " + NM_EMPLOYEE + ", " + KN_EMPLOYEE + ", " +
MAIL_ADDRESS + ", " + PASSWORD + ", " + ID_DEPARTMENT);
sql.append(" ) ");
sql.append(" VALUES ");
sql.append(" ( ?, ?, ?, ?, ?) ");
try {
this.stmt = con.prepareStatement(sql.toString());
this.stmt.setString(1,name );
this.stmt.setString(2,kana );
this.stmt.setString(3,email );
this.stmt.setString(4,password );
this.stmt.setInt(5,idDep );
stmt.executeUpdate();
}finally {
DbUtil.closeStatement(this.stmt);
}
}
public void empUpdate(Integer id, String name, String kana, String email,
String password, Integer idDep)throws SQLException, ClassNotFoundException{
StringBuilder sql = new StringBuilder();
sql.append(" UPDATE ");
sql.append(" " + TBL_NAME);
sql.append(" SET ");
sql.append(" " + NM_EMPLOYEE + "= ?,");
sql.append(" " + KN_EMPLOYEE + "= ?,");
sql.append(" " + MAIL_ADDRESS + "= ?,");
sql.append(" " + PASSWORD + "= ?,");
sql.append(" " + ID_DEPARTMENT + "= ?");
sql.append(" WHERE ");
sql.append(ID_EMPLOYEE + "= ?");
try {
this.stmt = con.prepareStatement(sql.toString());
this.stmt.setString(1,name );
this.stmt.setString(2,kana );
this.stmt.setString(3,email );
this.stmt.setString(4,password );
this.stmt.setInt(5,idDep );
this.stmt.setInt(6, id);
stmt.executeUpdate();
}finally {
DbUtil.closeStatement(this.stmt);
}
}
}

View File

@@ -1,60 +1,47 @@
package com.rhizome.example.dto; package com.rhizome.example.dto;
public class EmployeeDTO { public class EmployeeDTO {
private Integer id;
//Employeeテーブルのカラム分のフィールド private String name;
private Integer id_employee; private String kana;
private String nm_employee; private String email;
private String kn_employee; private String pass;
private String mail_address; private Integer idDep;
private String password;
private Integer id_department; public Integer getId() {
return id;
public Integer getId_employee() {
return id_employee;
} }
public void setId_employee(Integer id_employee) { public void setId(Integer id) {
this.id_employee = id_employee; this.id = id;
} }
public String getNm_employee() { public String getName() {
return nm_employee; return name;
} }
public void setNm_employee(String nm_employee) { public void setName(String name) {
this.nm_employee = nm_employee; this.name = name;
} }
public String getKn_employee() { public String getKana() {
return kn_employee; return kana;
} }
public void setKn_employee(String kn_employee) { public void setKana(String kana) {
this.kn_employee = kn_employee; this.kana = kana;
} }
public String getMail_address() { public String getEmail() {
return mail_address; return email;
} }
public void setMail_address(String mail_address) { public void setEmail(String email) {
this.mail_address = mail_address; this.email = email;
} }
public String getPassword() { public String getPass() {
return password; return pass;
} }
public void setPassword(String password) { public void setPass(String pass) {
this.password = password; this.pass = pass;
} }
public Integer getId_department() { public Integer getIdDep() {
return id_department; return idDep;
} }
public void setId_department(Integer id_department) { public void setIdDep(Integer idDep) {
this.id_department = id_department; this.idDep = idDep;
} }
public Object getPrimaryKeyValue() { }
// TODO 自動生成されたメソッド・スタブ
return null;
}
}

View File

@@ -54,10 +54,13 @@ public class Main {
empSelect(); empSelect();
break; break;
case "2": case "2":
empInsert();
break; break;
case "3": case "3":
empUpdate();
break; break;
case "4": case "4":
empDelete();
break; break;
case "9": case "9":
return; return;
@@ -79,7 +82,7 @@ public class Main {
public static void empSelect() throws ClassNotFoundException, SQLException { public static void empSelect() throws ClassNotFoundException, SQLException {
List<EmployeeDTO> empList = new ArrayList<>(); List<EmployeeDTO> empList = new ArrayList<>();
Connection con = DbUtil.getConnection(); Connection con = DbUtil.getConnection();
EmployeeDAO empDao = new EmployeeDAO(); EmployeeDAO empDao = new EmployeeDAO(con);
System.out.println("1:全検索 2:条件検索 それ以外:戻る"); System.out.println("1:全検索 2:条件検索 それ以外:戻る");
String select = sc.nextLine(); String select = sc.nextLine();
try { try {
@@ -88,23 +91,23 @@ public class Main {
empList = empDao.selectAll(); empList = empDao.selectAll();
break; break;
case "2": case "2":
String id = sc.nextLine();//IDを入力 String strId =inputCheck("ID", true);
int num = Integer.valueOf(id);//String型のIDをint型に変換 int ID = Integer.parseInt(strId);
empList = empDao.selectById​(num); empList = empDao.selectById(ID);
break; break;
default: default:
return; return;
} }
if(empList.isEmpty()) {
System.out.println("入力された値で情報がみつかりませんでした");
}else{
for (EmployeeDTO emp : empList) { for (EmployeeDTO emp : empList) {
System.out.println(emp.getId_employee() + "\t" System.out.println(emp.getId() + "\t" + emp.getName() + "\t" +
+ emp.getNm_employee() + "\t" emp.getKana() + "\t" + emp.getEmail() + "\t" + emp.getPass() + "\t" + emp.getIdDep());
+ emp.getKn_employee() + "\t" }
+ emp.getMail_address() + "\t"
+ emp.getPassword() + "\t"
+ emp.getId_department());
} }
} finally { } finally {
DbUtil.closeConnection(); DbUtil.closeConnection(empDao.con);
} }
} }
@@ -133,9 +136,6 @@ public class Main {
* @param flg * @param flg
* 数値チェック可否フラグ * 数値チェック可否フラグ
* @return * @return
* @throws SQLException
* @throws ClassNotFoundException
* @throws NumberFormatException
*/ */
public static String inputCheck(String titleName, boolean flg) { public static String inputCheck(String titleName, boolean flg) {
String str = null; String str = null;
@@ -155,11 +155,86 @@ public class Main {
continue; continue;
} }
} }
} }
break; break;
} }
return str; return str;
} }
}
public static void empDelete() throws ClassNotFoundException, SQLException {
//リスト作成
List<EmployeeDTO> empList = new ArrayList<>();
//DB接続
Connection con = DbUtil.getConnection();
//DAOインスタンス生成
EmployeeDAO empDao = new EmployeeDAO(con);
try {
//入力された文字列をdelIdに保存
String delId =inputCheck("ID", true);
//入力された文字列を整数に変換して保存
int ID = Integer.parseInt(delId);
//入力されたIDに一致するデータを保存
empList = empDao.selectById(ID);
//リストが空=一致なし
if(empList.isEmpty()) {
System.out.println("入力された値で情報がみつかりませんでした");
}else {
System.out.println("指定されたIDの情報を削除します? Y/y");
//削除の同意受付
String agr = sc.nextLine();
//同意が得られたら
if("Y".equals(agr) || "y".equals(agr)) {
//削除メソッド実行し削除
empDao.empDelete(ID);
System.out.println("削除が完了しました");
}
}
}finally {
DbUtil.closeConnection(empDao.con);
}
}
public static void empInsert() throws ClassNotFoundException, SQLException {
Connection con = DbUtil.getConnection();
EmployeeDAO empDao = new EmployeeDAO(con);
try {
String name = inputCheck("社員名",false);
String kana = inputCheck("フリガナ", false);
String email = inputCheck("メールアドレス", false);
String password = inputCheck("パスワード", false);
String depId = inputCheck("部署ID", true);
int dID = Integer.parseInt(depId);
empDao.empInsert(name,kana,email,password,dID);
System.out.println("登録が完了しました");
}finally {
DbUtil.closeConnection(empDao.con);
}
}
public static void empUpdate() throws ClassNotFoundException, SQLException{
List<EmployeeDTO> empList = new ArrayList<>();
Connection con = DbUtil.getConnection();
EmployeeDAO empDao = new EmployeeDAO(con);
try {
String delId =inputCheck("ID", true);
int ID = Integer.parseInt(delId);
empList = empDao.selectById(ID);
if(empList.isEmpty()) {
System.out.println("入力された値で情報がみつかりませんでした");
return;
}
String name = inputCheck("社員名",false);
String kana = inputCheck("フリガナ", false);
String email = inputCheck("メールアドレス", false);
String password = inputCheck("パスワード", false);
String depId = inputCheck("部署ID", true);
int dID = Integer.parseInt(depId);
empDao.empUpdate(ID,name,kana,email,password,dID);
System.out.println("更新が完了しました");
}finally {
DbUtil.closeConnection(empDao.con);
}
}
}

View File

@@ -5,7 +5,6 @@ import java.sql.DriverManager;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
import java.sql.SQLException; import java.sql.SQLException;
public class DbUtil { public class DbUtil {
// 定数定義(共通) // 定数定義(共通)
private static final String DB_HOST = "127.0.0.1"; private static final String DB_HOST = "127.0.0.1";
@@ -45,26 +44,15 @@ public class DbUtil {
* 生成されたConnectionを返却する * 生成されたConnectionを返却する
* ※Connection生成には上記の定数を活用してください * ※Connection生成には上記の定数を活用してください
*/ */
//DB接続用メソッドを作成する public static Connection getConnection() throws ClassNotFoundException, SQLException{
public static Connection getConnection() throws ClassNotFoundException { Class.forName("com.mysql.cj.jdbc.Driver");
//データベースの接続オブジェクトを初期化 con = DriverManager.getConnection(
Connection con = null; "jdbc:mysql://127.0.0.1:3306/rezodb",
// JDBCドライバの読み込み "rezouser",
Class.forName("com.mysql.cj.jdbc.Driver"); "Rezo_0000"
);
// Connectionの生成 return con;
try { }
con = DriverManager.getConnection(
"jdbc:mysql://127.0.0.1:3306/rezodb" // データベース
, "rezouser" // ユーザ
, "Rezo_0000" // パスワード
);
} catch (SQLException e) {
e.printStackTrace();
}
return con;
}
/* /*
* TODO 以下の仕様でメソッドを作成してください。 * TODO 以下の仕様でメソッドを作成してください。
@@ -75,15 +63,11 @@ public class DbUtil {
* 例外 :SQLException * 例外 :SQLException
* 処理 :引数のDBステートメントがnullでない場合、そのDBステートメントをクローズする * 処理 :引数のDBステートメントがnullでない場合、そのDBステートメントをクローズする
*/ */
public static void closeStatement() { public static void closeStatement(PreparedStatement stmt) throws SQLException{
PreparedStatement stmt = null; if(stmt != null) {
try { stmt.close();
if (stmt != null) stmt.close(); }
} catch (SQLException e) { }
e.printStackTrace();
}
}
/* /*
* TODO 以下の仕様でメソッドを作成してください。 * TODO 以下の仕様でメソッドを作成してください。
@@ -94,12 +78,10 @@ public class DbUtil {
* 例外 :SQLException * 例外 :SQLException
* 処理 :引数のコネクションがnullでない場合、そのコネクションを切断する * 処理 :引数のコネクションがnullでない場合、そのコネクションを切断する
*/ */
public static void closeConnection() { public static void closeConnection(Connection con) throws SQLException{
try { if(con != null) {
if (con != null) con.close(); con.close();
} catch (SQLException e) { }
e.printStackTrace(); }
}
}
} }