티스토리 뷰
* 테이블에 컬럼 없어도 RANK, TOTAL, AVG 가져올 수 있음*
* 추가된 데이터 갯수 위해 쓰이는 변수 n의 역할
try { //쿼리문 작성
String sql = "SELECT MID, NAME, KOR, ENG, MAT, RANK() OVER(ORDER BY (KOR+ENG+MAT)/3 ) AS RANK FROM STUDENT ORDER BY MID";
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
//mid, name, kor, eng, mat // 총점/ 평균/ 학점 /결과 / 순위
while(rs.next()) {
entity = new Student();
entity.setMid(rs.getInt("MID"));
entity.setName(rs.getString("NAME"));
entity.setKor(rs.getInt("KOR"));
entity.setEng(rs.getInt("ENG"));
entity.setMat(rs.getInt("MAT"));
entity.setRank(rs.getInt("RANK"));
entity.getTot();
entity.getAvg();
entity.getGrade();
entity.getResult();
GUIDE LINE
**쿼리문 버퍼로
create table student(
mid number primary key,
name varchar2(15) not null,
kor number,
eng number,
mat number
);
[문제 26] 다음 프로그램을 작성하시오
(1) 프로젝트명 : ScoreProject
(2) 테이블명: student
컬럼명 : mid 숫자, 기본키
name 가변형(15),널값허용안함
kor 숫자
eng 숫자
mat 숫자
시퀀스 : m_mid(1부터 1씩증가)
입력자료 : 민들래, 90, 88, 75
진달래, 80, 88, 65
(3)구조
ScoreProject
src
table_schma
student.sql
common
JdbcTemplate.java
com.edu.view
StudentMain.java <---main()메서드
StudentView.java
com.edu.entity
Student.java
com.edu.dao
StudentDAO.java
com.edu.controller
StudentController.java
(4)조건
1) StudentMain : 입력 코드를 완성한다
menu()는 StudentMain에서 만들고, 모든 결과 출력은 StudentView에서 한다
2) Student
-mid:int
-name:String
-kor:int
-eng:int
-mat:int
-rank:int --순위
+Student()
+Student(mid:int,name:String,kor:int,eng:int,mat:int,rank:int)
+getter & setter
+getTot():int
+getAvg():double
+getGrade():char
+getResult():String
+toString():String
3) StudentController
dao:StudentDao
view:StudentView
+StudentController() --> dao, view객체의 메모리 할당
+getStudentList():void
+getStudent(name:String):void
+insertStudent(ob:Student):String --> 국,영,수 점수가 0~100사이인지 확인한후 dao로 값 전달
0~100이외의 값이면 StudentMain으로
"입력값에 오류가 있습니다"를 리턴(유효성 검사)
+deleteStudent(name:String):void
4) StudentDAO
+getStudentList():ArrayList<Student> ==> 전체보기
+getStudent(name:String):Student ==> 찾기
+insertStudent(ob:Student):int ==> 추가
+deleteStudent(name:String):int ==> 삭제
5) StudentView
+insertStudent(n:int, name:String):void
+deleteStudent(n:int, name:String):void
+getStudentList(list:ArrayList<Student>):void
+getStudent(ob:Student):void
6) StudentMain
sc:Scanner
control:StudentController
entity:Student
+StudentMain() -- sc, control, entity 객체의 메모리 할당 또는 초기화
+menu():void -- 메뉴화면 만들기
+main():void -- main()에서 아래 코드만 추가하기
new StudentMain():menu();
[입.출력화면]
1.추가 2.삭제 3.전체보기 4.찾기 5.종료
선택(1~5) : 1
이름: 강호동
국어: 90
영어: 80
수학: 100
강호동을 추가했습니다
1.추가 2.삭제 3.전체보기 4.찾기 5.종료
선택(1~5) : 1
이름: 강호동
국어: 90
영어: 80
수학: 150
입력값에 오류가 있습니다
1.추가 2.삭제 3.전체보기 4.찾기 5.종료
선택(1~5) : 3
번호 이름 국어 영어 수학 총점 평균 학점 결과 순위
----------------------------------------------------------------------
1 민들래 90 88 75 253 84.33 B 합격 2
2 진달래 65 55 43 163 54.33 F 불합격 3
3 강호동 90 80 100 270 90.00 A 합격 1
1.추가 2.삭제 3.전체보기 4.찾기 5.종료
선택(1~5) : 4
찾는사람 : 강호동
강호동의 총점은 270점이고 평균은 90.00점입니다 <---toString()으로 처리하시오
학점은 A이고 결과는 합격입니다 NumberFormat를 이용해서 소수점 2째자리까지 출력하시오
1.추가 2.삭제 3.전체보기 4.찾기 5.종료
선택(1~5) : 2
삭제할사람 : 강호동
삭제되었습니다
1.추가 2.삭제 3.전체보기 4 .찾기 5.종료
선택(1~5) : 5
*** 작업끝 ****
list.add(entity);
com.edu.controller 패키지
> StudentController
package com.edu.controller;
//View와 Model에서 중
import java.sql.SQLException;
import java.util.List;
import com.edu.dao.StudentDAO;
import com.edu.entity.Student;
import com.edu.view.StudentView;
// View와 Model에서 중간처리하는 역할
public class StudentController {
StudentDAO dao=null;
StudentView view=null;
public StudentController() {
dao=new StudentDAO();
view=new StudentView();
}
public void insertSQL(Student entity){
int n=dao.insertStudent(entity);
view.insertStudent(n, entity);
}
public void getStudentList(){
List<Student> list=dao.getStudentList();
view.getStudentList(list);
}
public boolean getStudent(String name){
Student ob=dao.getStudent(name);
view.getStudent(ob);
return (ob != null)?true:false;
}
public void deleteStudent(String name){
int n=dao.deleteStudent(name);
view.deleteStudent(name, n);
}
}
common 패키지
> JdbcTemplate
package common;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JdbcTemplate {
public static Connection getConnection() {
Connection conn = null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection(
"jdbc:oracle:thin:@127.0.0.1:1521:XE", "edu", "1234");
conn.setAutoCommit(false);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
public static boolean isConnection(Connection conn) {
boolean valid = true;
try {
if (conn == null || conn.isClosed())
valid = false;
} catch (SQLException e) {
valid = false;
e.printStackTrace();
}
return valid;
}
public static void commit(Connection conn) {
if (isConnection(conn)) {
try {
conn.commit();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void rollback(Connection conn) {
if (isConnection(conn)) {
try {
conn.rollback();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
// Connection객체 닫기
public static void close(Connection conn) {
if (isConnection(conn)) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
// Statement or PreparedStatement객체 닫기
public static void close(Statement stmt) {
try {
if (stmt != null)
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
// ResultSet 객체 닫기
public static void close(ResultSet rs) {
try {
if (rs != null)
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
com.edu.dao 패키지
> StudentDAO
package com.edu.dao;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
//DB연동 위한 클래스
import java.util.List;
import com.edu.entity.Student;
import static common.JdbcTemplate.close;
import static common.JdbcTemplate.commit;
import static common.JdbcTemplate.getConnection;
import static common.JdbcTemplate.rollback;
public class StudentDAO {
public List<Student> getStudentList() { // 전체보기
Connection conn = getConnection();
Statement stmt = null;
ResultSet rs = null;
List<Student> list = new ArrayList<>();
Student entity = null;
try { //쿼리문 작성
String sql = "SELECT MID, NAME, KOR, ENG, MAT, RANK() OVER(ORDER BY (KOR+ENG+MAT)/3 ) AS RANK FROM STUDENT ORDER BY MID";
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
//mid, name, kor, eng, mat // 총점/ 평균/ 학점 /결과 / 순위
while(rs.next()) {
entity = new Student();
entity.setMid(rs.getInt("MID"));
entity.setName(rs.getString("NAME"));
entity.setKor(rs.getInt("KOR"));
entity.setEng(rs.getInt("ENG"));
entity.setMat(rs.getInt("MAT"));
entity.setRank(rs.getInt("RANK"));
entity.getTot();
entity.getAvg();
entity.getGrade();
entity.getResult();
list.add(entity); //이거 add 안해주면 껍데기만 넘겨줘서 아무것도 안뜸
}
}catch(SQLException e){
e.printStackTrace();
}finally {
close(rs);
close(stmt);
close(conn);
}
return list;
}
public int insertStudent(Student entity) { //추가하기
Connection conn = getConnection();
Statement stmt = null;
int n = 0;
try {
String sql = "INSERT INTO STUDENT(MID, NAME, KOR, ENG, MAT) VALUES(M_MID.NEXTVAL,' "
+ entity.getName() + " ', ' " + entity.getKor() + " ', ' "+ entity.getMat() + "','" + entity.getEng() + "')";
stmt = conn.createStatement();
n = stmt.executeUpdate(sql);
if(n>0) {
commit(conn);
}
}catch(SQLException e){
e.printStackTrace();
rollback(conn);
}finally {
close(stmt);
close(conn);
}
return n;
}
public Student getStudent(String name) { //검색하기
Connection conn = getConnection();
Statement stmt = null;
ResultSet rs = null;
Student entity = null;
try {
String sql = "SELECT * FROM STUDENT WHERE NAME= '" + name + "'";
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
while(rs.next()) {
entity=new Student(); //얘를 안하니까 안뜨지
entity.setMid(rs.getInt("MID"));
entity.setName(rs.getString("NAME"));
entity.setKor(rs.getInt("KOR"));
entity.setEng(rs.getInt("ENG"));
entity.setMat(rs.getInt("MAT"));
}
}catch (SQLException e) {
e.printStackTrace();
}finally {
close(rs);
close(stmt);
close(conn);
}
return entity;
}
public int deleteStudent(String name) { // 삭제하기
Connection conn = getConnection();
Statement stmt = null;
int n = 0;
try {
String sql = "DELETE FROM STUDENT WHERE NAME = ' " + name + " ' ";
stmt = conn.createStatement();
n = stmt.executeUpdate(sql);
if(n > 0) {
commit(conn);
}
}catch(SQLException e) {
e.printStackTrace();
rollback(conn);
}finally {
close(stmt);
close(conn);
}
return n;
}
}
com.edu.entity 패키지
> Student
package com.edu.entity;
public class Student {
private int mid;
private String name;
private int kor;
private int eng;
private int mat;
private int rank;
public Student() {
super();
}
public Student(int mid, String name, int kor, int eng, int mat, int rank) {
super();
this.mid = mid;
this.name = name;
this.kor = kor;
this.eng = eng;
this.mat = mat;
this.rank = rank;
}
public int getMid() {
return mid;
}
public String getName() {
return name;
}
public int getKor() {
return kor;
}
public int getEng() {
return eng;
}
public int getMat() {
return mat;
}
public int getRank() { // 등수 만들기
return rank;
}
public void setMid(int mid) {
this.mid = mid;
}
public void setName(String name) {
this.name = name;
}
public void setKor(int kor) {
this.kor = kor;
}
public void setEng(int eng) {
this.eng = eng;
}
public void setMat(int mat) {
this.mat = mat;
}
public void setRank(int rank) {// 등수
this.rank = rank;
}
public int getTot() { //총점
return kor + eng + mat;
}
public double getAvg() { // 평균 / 소숫점 두자릿수는 출력시에 고치기
return (kor + eng+ mat)/3;
}
public char getGrade() { // 학점 // 소숫점 값 가져와서 int로 바꾸고 10으로 나누기
switch((int)getAvg()/10) {
case 10 :
return 'A';
case 9 :
return 'A';
case 8 :
return 'B';
case 7 :
return 'C';
case 6 :
return 'D';
default :
return 'F';
}
}
public String getResult() { // 결과
if(getGrade()=='F') {
return "불합격";
}else {
return "합격";
}
}
@Override
public String toString() { // --->출력문장 리턴(getTot, getAvg,getGrade, getResult이용)
return getName()+"의 총점은 "+getTot()+"점이고 평균은 "+getAvg()+"점입니다 "
+ "학점은 "+getGrade()+"이고 결과는 "+getResult()+"입니다";
}
}
com.edu.view 패키지
> StudentMain
package com.edu.view;
//6) StudentMain
//sc:Scanner
//control:StudentController
//entity:Student
//+StudentMain() -- sc, control, entity 객체의 메모리 할당 또는 초기화
//+menu():void -- 메뉴화면 만들기
//+main():void -- main()에서 아래 코드만 추가하기
//
import java.util.Scanner;
import com.edu.controller.StudentController;
import com.edu.entity.Student;
//StudentMain : 입력 코드를 완성한다
//menu()는 StudentMain에서 만들고, 모든 결과 출력은 StudentView에서 한다
public class StudentMain {
Scanner sc = null;
StudentController control = null;
Student entity = null;
public StudentMain() {
sc = new Scanner(System.in);
control = new StudentController();
entity = new Student();
}
// private int mid;
// private String name;
// private int kor;
// private int eng;
// private int mat;
// private int rank;
public void menu() {
int n = 0;
int mid = 0;
String name = null;
int kor = 0;
int eng = 0;
int mat = 0;
int rank = 0;
while(true) {
System.out.print("1.추가 2.삭제 3.전체보기 4.찾기 5.종료\r\n"
+ "선택(1~5) :");
n = sc.nextInt();
switch(n) {
case 1:
System.out.print("이름:"); entity.setName(sc.next());
System.out.print("국어:"); entity.setKor(Integer.parseInt(sc.next()));
System.out.print("영어:"); entity.setEng(Integer.parseInt(sc.next()));
System.out.print("수학:"); entity.setMat(Integer.parseInt(sc.next()));
control.insertSQL(entity);
break;
case 2:
System.out.print("삭제할 사람:"); name = sc.next();
control.deleteStudent(name);
System.out.print("삭제됐어용");
break;
case 3:
control.getStudentList();
break;
case 4:
System.out.print("찾는 사람:"); name = sc.next();
control.getStudent(name);
break;
case 5:
sc.close();
System.exit(0);
default:
System.out.println("다시 입력해라 바보양");
continue;
}
}
}
public static void main(String[] args) {
new StudentMain().menu();
}
}
> StudentView
package com.edu.view;
//+insertStudent(n:int, name:String):void
//+deleteStudent(n:int, name:String):void
//+getStudentList(list:ArrayList<Student>):void
//+getStudent(ob:Student):void
import java.util.List;
import com.edu.entity.Student;
public class StudentView {
public void insertStudent(int n, Student entity) { // 입력
if(n>0) {
System.out.println( entity.getName()+ "을 추가했습니다");
}else {
System.out.println("데이터 추가하지 못했지롱");
}
}
public void deleteStudent(String name, int n) { //삭제
if(n> 0) {
System.out.println("삭제할 사람 : "+name);
System.out.println("삭제되었슴당");
}else {
System.out.println("다시 잘 입력하세용");
}
}
public void getStudentList(List<Student> list) { // 전체보기
if(list != null) {
System.out.println("번호 이름 국어 영어 수학 총점 평균 학점 결과 순위\r\n"
+ "----------------------------------------------------------------------");
for(Student ob : list) {
System.out.println(ob.getMid()+" "+ob.getName()+" "+ob.getKor()+" "+ob.getEng()+" "+ob.getMat()+" "
+ob.getTot()+" "+String.format("%.2f", ob.getAvg())+" "+ob.getGrade()+" "+ob.getResult() + " "+ob.getRank());
}
}
}
public void getStudent(Student ob) { // 검색하기
if(ob == null) {
System.out.println("찾는 사람이 없습니다");
}else {
System.out.println("찾는 사람 :" + ob.getName());
System.out.println(ob.toString());
}
}
}
student.sql
--(2) 테이블명: student
-- 컬럼명 : mid 숫자, 기본키
-- name 가변형(15),널값허용안함
-- kor 숫자
-- eng 숫자
-- mat 숫자
-- 시퀀스 : m_mid(1부터 1씩증가)
-- 입력자료 : 민들래, 90, 88, 75
-- 진달래, 80, 88, 65
select * from tab;
select * from student;
create table student(
mid number primary key,
name varchar2(15) not null,
kor number,
eng number,
mat number
);
create sequence m_mid increment by 1 start with 1 nocycle nocache;
insert into student (mid, name, kor, eng, mat)
values (m_mid.nextval, '민들래', 90, 88, 75);
insert into student (mid, name, kor, eng, mat)
values (m_mid.nextval, '진달래', 80, 88, 65);
댓글