💡 PreparedStatemet 를 사용한 학생 관리 프로그램
✔️ model.vo
package com.kh.jdbc.day03.student.model.vo;
import java.sql.Date;
public class Student {
private String studentId;
private String studentPwd;
private String studentName;
private char gender;
private int age;
private String email;
private String phone;
private String address;
private String hobby;
private Date enrollDate;
public Student() {
super();
}
public Student(String studentId, String studentPwd, String studentName, char gender, int age, String email,
String phone, String address, String hobby) {
super();
this.studentId = studentId;
this.studentPwd = studentPwd;
this.studentName = studentName;
this.gender = gender;
this.age = age;
this.email = email;
this.phone = phone;
this.address = address;
this.hobby = hobby;
}
public Student(String studentPwd, String email, String phone, String address, String hobby) {
super();
this.studentPwd = studentPwd;
this.email = email;
this.phone = phone;
this.address = address;
this.hobby = hobby;
}
public Student(String studentId, String studentPwd) {
super();
this.studentId = studentId;
this.studentPwd = studentPwd;
}
public String getStudentId() {
return studentId;
}
public void setStudentId(String studentId) {
this.studentId = studentId;
}
public String getStudentPwd() {
return studentPwd;
}
public void setStudentPwd(String studentPwd) {
this.studentPwd = studentPwd;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public char getGender() {
return gender;
}
public void setGender(char gender) {
this.gender = gender;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getHobby() {
return hobby;
}
public void setHobby(String hobby) {
this.hobby = hobby;
}
public Date getEnrollDate() {
return enrollDate;
}
public void setEnrollDate(Date enrollDate) {
this.enrollDate = enrollDate;
}
@Override
public String toString() {
return "학생 [아이디 =" + studentId + ", 비밀번호 =" + studentPwd + ", 이름 =" + studentName
+ ", 성별 =" + gender + ", 나이 =" + age + ", 이메일 =" + email + ", 전화번호 =" + phone + ", 주소 ="
+ address + ", 취미 =" + hobby + ", 가입일 =" + enrollDate + "]";
}
}
✔️ run
package com.kh.jdbc.day03.student.run;
import com.kh.jdbc.day03.student.view.StudentView;
public class MainRun {
public static void main(String [] args) {
StudentView view = new StudentView();
view.studentProgram();
}
}
✔️ view
package com.kh.jdbc.day03.student.view;
import java.util.List;
import java.util.Scanner;
import com.kh.jdbc.day03.student.controller.StudentController;
import com.kh.jdbc.day03.student.model.vo.Student;
public class StudentView {
private StudentController controller;
public StudentView() {
controller = new StudentController();
}
public void studentProgram() {
Student student = null;
List<Student> sList = null;
int result = 0;
theEnd :
while(true) {
int input = printMenu();
switch(input) {
case 1 :
sList = controller.selectAllStudent();
printAllStudent(sList);
break;
case 2 :
String studentId = inputStdId("검색");
student = controller.printStudentById(studentId);
printOneStudent(student);
break;
case 3 :
String studentName = inputStdName();
sList = controller.selectAllByName(studentName);
printAllStudent(sList);
break;
case 4 :
student = inputStudentInfo();
result = controller.insertStudent(student);
break;
case 5 :
studentId = inputStdId("수정");
student = controller.printStudentById(studentId);
if(student != null) {
student = modifyStudent();
student.setStudentId(studentId);
result = controller.updateStudent(student);
} else {
displayError("해당 정보가 존재하지 않습니다.");
}
break;
case 6 :
studentId = inputStdId("삭제");
result = controller.deleteStudent(studentId);
if(result > 0) {
displaySuccess("삭제 성공");
} else {
displayError("해당 정보가 존재하지 않습니다.");
}
break;
case 9 :
student = inputLoginInfo();
student = controller.studentLogin(student);
if(student != null) {
displaySuccess("로그인 성공");
} else {
displayError("해당 정보가 존재하지 않습니다.");
}
break;
case 0 :
break theEnd;
}
}
}
private void displaySuccess(String message) {
System.out.println("[서비스 성공] : "+ message);
}
private void displayError(String message) {
System.out.println("[서비스 실패] : "+ message);
}
private Student modifyStudent() {
Scanner sc = new Scanner(System.in);
System.out.println("===== 학생 정보 수정 =====");
System.out.print("비밀번호 : ");
String studentPw = sc.next();
System.out.print("이메일 : ");
String email = sc.next();
System.out.print("전화번호 : ");
String phone = sc.next();
System.out.print("주소 : ");
sc.nextLine();
String address = sc.nextLine();
System.out.print("취미(,로 구분) : ");
String hobby = sc.next();
Student student = new Student(studentPw, email, phone, address, hobby);
return student;
}
private Student inputStudentInfo() {
Scanner sc = new Scanner(System.in);
System.out.print("아이디 : ");
String studentId = sc.next();
System.out.print("비밀번호 : ");
String studentPw = sc.next();
System.out.print("이름 : ");
String studentName = sc.next();
System.out.print("성별 : ");
char gender = sc.next().charAt(0);
System.out.print("나이 : ");
int age = sc.nextInt();
System.out.print("이메일 : ");
String email = sc.next();
System.out.print("전화번호 : ");
String phone = sc.next();
System.out.print("주소 : ");
sc.nextLine();
String address = sc.nextLine();
System.out.print("취미(,로 구분) : ");
String hobby = sc.nextLine();
Student student = new Student(studentId, studentPw, studentName, gender, age, email, phone, address, hobby);
return student;
}
private Student inputLoginInfo() {
Scanner sc = new Scanner(System.in);
System.out.println("===== 학생 로그인 =====");
System.out.print("아이디 : ");
String studentID = sc.nextLine();
System.out.print("비밀번호 : ");
String studentPw = sc.nextLine();
Student student = new Student(studentID, studentPw);
System.out.println(student.toString());
return student;
}
private String inputStdName() {
Scanner sc = new Scanner(System.in);
System.out.print("검색할 이름 입력 : ");
String studentName = sc.next();
return studentName;
}
private String inputStdId(String category) {
Scanner sc = new Scanner(System.in);
System.out.print(category + "할 아이디 입력 : ");
String studentId = sc.next();
return studentId;
}
private void printOneStudent(Student student) {
System.out.println("====== 학생 정보 조회(아이디) ======");
System.out.printf("이름 : %s, 나이 : %d, 아이디: %s, 성별 %s, 이메일 : %s, 전화번호 : %s, 주소 : %s, 취미 : %s, 가입날짜 : %s\n"
, student.getStudentName()
, student.getAge()
, student.getStudentId()
, student.getGender()
, student.getEmail()
, student.getPhone()
, student.getAddress()
, student.getHobby()
, student.getEnrollDate());
}
private void printAllStudent(List<Student> sList) {
System.out.println("====== 학생 전체 조회 ======");
for(Student student : sList) {
System.out.printf("이름 : %s, 나이 : %d, 아이디: %s, 성별 %s, 이메일 : %s, 전화번호 : %s, 주소 : %s, 취미 : %s, 가입날짜 : %s\n"
, student.getStudentName()
, student.getAge()
, student.getStudentId()
, student.getGender()
, student.getEmail()
, student.getPhone()
, student.getAddress()
, student.getHobby()
, student.getEnrollDate());
}
}
private int printMenu() {
Scanner sc = new Scanner(System.in);
System.out.println("===== 학생관리 프로그램 =====");
System.out.println("9. 학생 로그인");
System.out.println("1. 학생 전체 조회");
System.out.println("2. 학생 아이디로 조회");
System.out.println("3. 학생 이름으로 조회");
System.out.println("4. 학생 정보 등록");
System.out.println("5. 학생 정보 수정");
System.out.println("6. 학생 정보 삭제");
System.out.println("0. 프로그램 종료");
System.out.print("메뉴 선택 : ");
int input = sc.nextInt();
return input;
}
}
✔️ controller
package com.kh.jdbc.day03.student.controller;
import java.util.List;
import com.kh.jdbc.day03.student.model.dao.StudentDAO;
import com.kh.jdbc.day03.student.model.vo.Student;
public class StudentController {
private StudentDAO sDao;
public StudentController() {
sDao = new StudentDAO();
}
public Student printStudentById(String studentId) {
Student student = sDao.selectOneById(studentId);
return student;
}
public List<Student> selectAllStudent() {
List<Student> sList = sDao.selectAll();
return sList;
}
public List<Student> selectAllByName(String studentName) {
List<Student> sList = sDao.selectOneByName(studentName);
return sList;
}
public int insertStudent(Student student) {
int result = sDao.insertStudent(student);
return result;
}
public int deleteStudent(String studentId) {
int result = sDao.deleteStudent(studentId);
return result;
}
public int updateStudent(Student student) {
int result = sDao.updateStudent(student);
return 0;
}
public Student studentLogin(Student student) {
Student result = sDao.selectLoginInfo(student);
return result;
}
}
✔️ model.dao
package com.kh.jdbc.day03.student.model.dao;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import com.kh.jdbc.day03.student.model.vo.Student;
public class StudentDAO {
private final String DRIVER_NAME = "oracle.jdbc.driver.OracleDriver";
private final String URL = "jdbc:oracle:thin:@127.0.0.1:1521:xe";
private final String USER = "STUDENT";
private final String PASSWORD = "STUDENT";
public List<Student> selectAll() {
String query = "SELECT * FROM STUDENT_TBL";
List<Student> sList = new ArrayList<Student>();
Connection conn = null;
Statement stmt = null;
ResultSet rset = null;
try {
Class.forName(DRIVER_NAME);
conn = DriverManager.getConnection(URL, USER, PASSWORD);
stmt = conn.createStatement();
rset = stmt.executeQuery(query);
while (rset.next()) {
Student student = rsetToStudent(rset);
sList.add(student);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
rset.close();
stmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return sList;
}
public List<Student> selectOneByName(String studentName) {
List<Student> sList = new ArrayList<Student>();
String query = "SELECT * FROM STUDENT_TBL WHERE STUDENT_NAME = ?";
Student student = null;
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rset = null;
try {
Class.forName(DRIVER_NAME);
conn = DriverManager.getConnection(URL, USER, PASSWORD);
pstmt = conn.prepareStatement(query);
pstmt.setString(1, studentName);
rset = pstmt.executeQuery();
while(rset.next()) {
student = rsetToStudent(rset);
sList.add(student);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
rset.close();
pstmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return sList;
}
public Student selectOneById(String studentId) {
String query = "SELECT * FROM STUDENT_TBL WHERE STUDENT_ID = ?";
Student student = null;
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rset = null;
try {
Class.forName(DRIVER_NAME);
conn = DriverManager.getConnection(URL, USER, PASSWORD);
pstmt = conn.prepareStatement(query);
pstmt.setString(1, studentId);
rset = pstmt.executeQuery();
if(rset.next()) {
student = rsetToStudent(rset);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
rset.close();
pstmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return student;
}
public Student selectLoginInfo(Student student) {
String query = "SELECT * FROM STUDENT_TBL WHERE STUDENT_ID = ? AND STUDENT_PWD = ?";
Student result = null;
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rset = null;
try {
Class.forName(DRIVER_NAME);
conn = DriverManager.getConnection(URL, USER, PASSWORD);
pstmt = conn.prepareStatement(query);
pstmt.setString(1, student.getStudentId());
pstmt.setString(2, student.getStudentPwd());
rset = pstmt.executeQuery();
if(rset.next()) {
result = rsetToStudent(rset);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
rset.close();
pstmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return result;
}
public int insertStudent(Student student) {
String query = "INSERT INTO STUDENT_TBL VALUES(?,?,?,?,?,?,?,?,?,SYSDATE)";
int result = -1;
Connection conn = null;
PreparedStatement pstmt = null;
try {
Class.forName(DRIVER_NAME);
conn = DriverManager.getConnection(URL, USER, PASSWORD);
pstmt = conn.prepareStatement(query);
pstmt.setString(1, student.getStudentId());
pstmt.setString(2, student.getStudentPwd());
pstmt.setString(3, student.getStudentName());
pstmt.setString(4, String.valueOf(student.getGender()));
pstmt.setInt(5, student.getAge());
pstmt.setString(6, student.getEmail());
pstmt.setString(7, student.getPhone());
pstmt.setString(8, student.getAddress());
pstmt.setString(9, student.getHobby());
result = pstmt.executeUpdate();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
pstmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return result;
}
public int deleteStudent(String studentId) {
String query = "DELETE FROM STUDENT_TBL WHERE STUDENT_ID = ?";
int result = -1;
Connection conn = null;
PreparedStatement pstmt = null;
try {
Class.forName(DRIVER_NAME);
conn = DriverManager.getConnection(URL, USER, PASSWORD);
pstmt = conn.prepareStatement(query);
pstmt.setString(1, studentId);
result = pstmt.executeUpdate();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
pstmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return result;
}
public int updateStudent(Student student) {
String query = "UPDATE STUDENT_TBL SET STUDENT_PWD = ?, EMAIL = ?, PHONE = ?, ADDRESS = ?, HOBBY = ? WHERE STUDENT_ID = ?";
int result = -1;
Connection conn = null;
PreparedStatement pstmt = null;
try {
Class.forName(DRIVER_NAME);
conn = DriverManager.getConnection(URL, USER, PASSWORD);
pstmt = conn.prepareStatement(query);
pstmt.setString(1, student.getStudentPwd());
pstmt.setString(2, student.getEmail());
pstmt.setString(3, student.getPhone());
pstmt.setString(4, student.getAddress());
pstmt.setString(5, student.getHobby());
pstmt.setString(6, student.getStudentId());
result = pstmt.executeUpdate();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
pstmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return result;
}
private Student rsetToStudent(ResultSet rset) throws SQLException {
Student student = new Student();
student.setStudentId(rset.getString(1));
student.setStudentPwd(rset.getString("STUDENT_PWD"));
student.setStudentName(rset.getString("STUDENT_NAME"));
student.setGender(rset.getString("GENDER").charAt(0));
student.setAge(rset.getInt("AGE"));
student.setEmail(rset.getString("EMAIL"));
student.setPhone(rset.getString("PHONE"));
student.setAddress(rset.getString("ADDRESS"));
student.setHobby(rset.getString("HOBBY"));
student.setEnrollDate(rset.getDate("ENROLL_DATE"));
return student;
}
}