개인 프로젝트 - oracle DB를 연동한 GUI프로그램

jeong·2021년 8월 22일
2

Project

목록 보기
1/8

1.프로그램

개요 : GUI 프로그램(오라클 DB 연동, JFrame 활용)
주제 : 학원근처 맛집 관리프로그램

데이타베이스
=> 정보 : 음식점 이름, 전화번호, 주소, 거리(도보), 메모(맛평가/추천메뉴 등)

프로그램 구현 기능(CRUD)
1) 저장
=> 이름, 전화번호, 주소, 거리(도보), 메모를 입력받아 저장
=> 전화번호에 대한 중복 검사

2) 수정
=> 이름을 입력받아 맛집정보 검색 : 검색된 정보가 없는 경우 메세지 출력
=> 이름, 전화번호, 주소, 거리(도보) 를 입력받아 변경
=> 메모 추가할 수 있도록

3) 삭제
=> 이름을 입력받아 맛집 정보 삭제 : 삭제할 정보가 없는 경우 메세지 출력

4) 검색
=> 이름 검색과 거리 검색
=> 거리(도보)를 입력받아 맛집 정보 검색 : 검색된 정보가 없는 경우 메세지 출력
=> 저장된 모든 정보 검색 가능

5) 정보에 대한 유효성 검사


2.프로그램 구성


1) 입력필드 : 
정보 - 이름, 전화번호, 주소, 거리, 메모 
검색값 - 이름, 거리('숫자'+'분')로 검색

2) 버튼 : 
정보저장, 정보변경, 정보삭제, 맛집검색 버튼 상단배치
입력값을 안 넣고 맛집검색 버튼을 누르면 전체 데이터 출력  
이름 필드에 맛집 이름을 입력하고 맛집검색 버튼 눌러 사용
검색 필드에 거리를 입력하고 맛집검색 버튼을  눌러 사용

3) 테이블 :
오라클DB 연동
접속시 전체 데이터 출력 
메모값 제외 테이블 내용을 가운데로 정렬해줌 
테이블 구성 -
이름 :  NOT NULL 
전화번호 : PRIMARY KEY
주소 : 생략가능
거리 :  NOT NULL 
메모 : 생략가능 


3. 프로그램 기능구현

1) 저장

2) 수정

3) 검색

  • 이름 검색
  • 거리 검색

    -전체 검색

    4) 삭제

4. 프로그램 유효성 검사 : 입력값 오류와 확인



5. 코드

DB

CREATE TABLE LUNCHMANAGE (
    NAME VARCHAR2(30) NOT NULL,
    PHONE VARCHAR2(20) PRIMARY KEY, 
    ADDRESS VARCHAR2(40),
    DISTANCE VARCHAR2(10) NOT NULL,
    MEMO VARCHAR2(80)
    );
DESC LUNCHMANAGE; 

INSERT INTO LUNCHMANAGE VALUES('덕이닭찜','02-552-0757','강남구 테헤란로4길 46','10분','닭갈비+묵사발+볶음밥 맛있다');
INSERT INTO LUNCHMANAGE VALUES('봉된장','02-555-5300','강남구 테헤란로4길 38-3','5분','밥 맛있는데 양 적음');
INSERT INTO LUNCHMANAGE VALUES('알라보','0507-1318-0939','강남구 테헤란로 129','6분','매장이 작고 사람이 많다');
INSERT INTO LUNCHMANAGE VALUES('석기정부대찌개','02-561-6661','강남구 테헤란로8길 11-8','4분','양많고 맛있다, 메뉴는 2개뿐');
INSERT INTO LUNCHMANAGE VALUES('대독장','02-552-7745','강남구 논현로85길 59','5분','계란후라이무한, 돼지고기는 별로');
INSERT INTO LUNCHMANAGE VALUES('보슬보슬','02-6014-1245','강남구 테헤란로8길 22','5분','양많음, 마늘칩떡볶이, 베이컨김밥 맛있당');
INSERT INTO LUNCHMANAGE VALUES('나이스샤워','02-558-6008','강남구 테헤란로10길 25','5분','웨이팅있음, 바질토마토 맛있다');
INSERT INTO LUNCHMANAGE VALUES('이필녀국밥','02-561-7760','강남구 테헤란로25길 42','12분','인생 뼈해장국집, 가격도 7000원');
INSERT INTO LUNCHMANAGE VALUES('탄탄면공방','0507-1346-2229','강남구 테헤란로4길 40','8분','향신료 강하지않고 국물 맛있다');
INSERT INTO LUNCHMANAGE VALUES('안사부','02-558-1769','강남구 테헤란로8길 32','6분','요일별 메뉴할인, 짬뽕 괜찮음');

SELECT * FROM LUNCHMANAGE;
COMMIT;

JAVA

LUNCHMANAGEDTO

package CrudProject; 

/*
이름       널?       유형           
-------- -------- ------------ 
NAME     NOT NULL VARCHAR2(30) 
PHONE    NOT NULL VARCHAR2(20) 
ADDRESS           VARCHAR2(40) 
DISTANCE NOT NULL VARCHAR2(10) 
MEMO              VARCHAR2(80) 
*/

public class LunchManageDTO {
	private String name;
	private String phone;
	private String address;
	private String distance;
	private String memo;
	
	public LunchManageDTO() {
		// TODO Auto-generated constructor stub
	}

	public LunchManageDTO(String name, String phone, String address, String distance, String memo) {
		super();
		this.name = name;
		this.phone = phone;
		this.address = address;
		this.distance = distance;
		this.memo = memo;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	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 getDistance() {
		return distance;
	}

	public void setDistance(String distance) {
		this.distance = distance;
	}

	public String getMemo() {
		return memo;
	}

	public void setMemo(String memo) {
		this.memo = memo;
	}
}

LUNCHMANAGEDAO

package CrudProject; 

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class LunchManageDAO extends JdbcDAO{
	//1
	private static LunchManageDAO _dao;
	
	//2 생성자의 은닉화 선언
	private LunchManageDAO() {
		// TODO Auto-generated constructor stub
	}
	
	//3 정적영역에서 클래스의 인스턴스를 생성하여 참조필드에 저장
	static {
		_dao=new LunchManageDAO();
	}
	
	//4 참조필드에 저장된 인스턴스를 반환하는 메소드 작성
	public static LunchManageDAO getDAO() {
		return _dao;
	}
	
	//테이블에 새로운 행으로 삽입, 정보 저장 
	public int insertLunchManage(LunchManageDTO lunchmanage) {
		Connection con=null;
		PreparedStatement pstmt=null;
		int rows=0;
		try {
			con=getConnection();
			
			String sql="insert into lunchmanage values(?,?,?,?,?)";
			pstmt=con.prepareStatement(sql);
			pstmt.setString(1, lunchmanage.getName());
			pstmt.setString(2, lunchmanage.getPhone());
			pstmt.setString(3, lunchmanage.getAddress());
			pstmt.setString(4, lunchmanage.getDistance());
			pstmt.setString(5, lunchmanage.getMemo());
			
			rows=pstmt.executeUpdate();
		} catch (SQLException e) {
			System.out.println("[에러]insertlunchmanage() 메소드의 SQL 오류 = "+e.getMessage());
		} finally {
			close(con, pstmt);
		} return rows;
	}	
	
	//정보 변경 
	public int updateLunchManage(LunchManageDTO lunchmanage) {
		Connection con=null;
		PreparedStatement pstmt=null;
		int rows=0;
		try {
			con=getConnection();
			String sql="update lunchmanage set name=?,address=?,distance=?,memo=? where phone=?";
			pstmt=con.prepareStatement(sql);
			pstmt.setString(1, lunchmanage.getName());
			pstmt.setString(2, lunchmanage.getAddress());
			pstmt.setString(3, lunchmanage.getDistance());
			pstmt.setString(4, lunchmanage.getMemo());
			pstmt.setString(5, lunchmanage.getPhone());
			
			rows=pstmt.executeUpdate();
		} catch (SQLException e) {
			System.out.println("[에러]updatelunchmanage() 메소드의 SQL 오류 = "+e.getMessage());
		} finally {
			close(con, pstmt);
		} return rows;
	}
	
	//정보 삭제 
	public int deleteLunchManage(String name) {
		Connection con=null;
		PreparedStatement pstmt=null;
		int rows=0;
		
		try {
			con=getConnection();
			
			String sql="delete from lunchmanage where name=?";
			pstmt=con.prepareStatement(sql);
			pstmt.setString(1, name); //
			
			rows=pstmt.executeUpdate();
		} catch (SQLException e) {
			System.out.println("[에러]deletelunchmanage() 메소드의 SQL 오류 = "+e.getMessage());
		} finally {
			close(con, pstmt);
		} 
		return rows;
	}
	
	// 이름 전달, 해당 이름 검색  
	//=> 단일행 검색 
	public LunchManageDTO selectNameLunchManage(String name) {
		Connection con=null;
		PreparedStatement pstmt=null;
		ResultSet rs=null;
		LunchManageDTO lunchmanage=null;
		try {
			con=getConnection();
			
			String sql="select * from lunchmanage where name=?";
			pstmt=con.prepareStatement(sql);
			pstmt.setString(1, name); //
			
			rs=pstmt.executeQuery();
			
			if(rs.next()) {
				//DTO 인스턴스 생성 - 인스턴스 필드에는 기본값 저장 
				lunchmanage=new LunchManageDTO();
				//검색행의 컬럼값을 DTO 인스턴스의 필드값으로 매핑 처리(Oracle >> Java)
				lunchmanage.setName(rs.getString("name"));
				lunchmanage.setPhone(rs.getString("phone"));
				lunchmanage.setAddress(rs.getString("address"));
				lunchmanage.setDistance(rs.getString("distance"));
				lunchmanage.setMemo(rs.getString("memo"));
			}
		} catch (SQLException e) {
			System.out.println("[에러]selectNameLunchManage() 메소드의 SQL 오류 = "+e.getMessage());
		} finally {
			close(con, pstmt);
		} 
		return lunchmanage;
	}
	
	//거리 전달
	//=> 단일행 검색 / 다중행 검색 
	public List<LunchManageDTO> selectDistanceLunchManageList(String distance) {
		Connection con=null;
		PreparedStatement pstmt=null;
		ResultSet rs=null;
		List<LunchManageDTO> lunchmanagerList=new ArrayList<LunchManageDTO>();
		try {
			con=getConnection();
			
			String sql="select * from LunchManage where distance=?";
			pstmt=con.prepareStatement(sql);
			pstmt.setString(1, distance); //
			
			rs=pstmt.executeQuery();
			
			while (rs.next()) {
				LunchManageDTO lunchmanage=new LunchManageDTO();
				lunchmanage.setName(rs.getString("name"));
				lunchmanage.setPhone(rs.getString("phone"));
				lunchmanage.setAddress(rs.getString("address"));
				lunchmanage.setDistance(rs.getString("distance"));
				lunchmanage.setMemo(rs.getString("memo"));
				lunchmanagerList.add(lunchmanage);
			}
		} catch (Exception e) {
			System.out.println("[에러] =selectDistanceLunchManageList() 메소드의 SQL 오류 = "+e.getMessage());
		} finally {
			close(con, pstmt, rs);
		} 
		return lunchmanagerList;
	}
	
	public List<LunchManageDTO> selectNameManageList(String name) {
		Connection con=null;
		PreparedStatement pstmt=null;
		ResultSet rs=null;
		List<LunchManageDTO> lunchmanagerList=new ArrayList<LunchManageDTO>();
		try {
			con=getConnection();
			
			String sql="select * from LunchManage where name=?";
			pstmt=con.prepareStatement(sql);
			pstmt.setString(1, name); //
			
			rs=pstmt.executeQuery();
			
			while (rs.next()) {
				LunchManageDTO lunchmanage=new LunchManageDTO();
				lunchmanage.setName(rs.getString("name"));
				lunchmanage.setPhone(rs.getString("phone"));
				lunchmanage.setAddress(rs.getString("address"));
				lunchmanage.setDistance(rs.getString("distance"));
				lunchmanage.setMemo(rs.getString("memo"));
				lunchmanagerList.add(lunchmanage);
			}
			
		} catch (Exception e) {
			System.out.println("[에러] =selectDistanceLunchManageList() 메소드의 SQL 오류 = "+e.getMessage());
		} finally {
			close(con, pstmt, rs);
		} 
		return lunchmanagerList;
	}
	
	//모든 학생 정보를 검색하여 반환하는 메소드 
	//=> 다중행 검색 
	public List<LunchManageDTO> selectAllLunchManagerList() {
		Connection con=null;
		PreparedStatement pstmt=null;
		ResultSet rs=null;
		List<LunchManageDTO> lunchmanagerList=new ArrayList<LunchManageDTO>();
		try {
			con=getConnection();
			
			String sql="select * from lunchmanage order by name";
			pstmt=con.prepareStatement(sql);
			
			rs=pstmt.executeQuery();
			
			while (rs.next()) {
				LunchManageDTO lunchmanage=new LunchManageDTO();
				lunchmanage.setName(rs.getString("name"));
				lunchmanage.setPhone(rs.getString("phone"));
				lunchmanage.setAddress(rs.getString("address"));
				lunchmanage.setDistance(rs.getString("distance"));
				lunchmanage.setMemo(rs.getString("memo"));
				lunchmanagerList.add(lunchmanage);
			}
		} catch (SQLException e) {
			System.out.println("[에러] =selectAllLunchManageList() 메소드의 SQL 오류 = "+e.getMessage());
		} finally {
			close(con, pstmt, rs);
		}
		return lunchmanagerList; 
	}
}

LUNCHMANAGEGUIAPP

package CrudProject; 

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
import java.util.Vector;
import java.util.regex.Pattern;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumnModel;

public class LunchManageGUIApp extends JFrame implements ActionListener { 
	private static final long serialVersionUID = 1L;
	private JTable table;
	
	private JPanel contentPane;
	private JTextField nameTF;
	private JTextField phoneTF;
	private JTextField addressTF;
	private JTextField distanceTF;
	private JTextField memoTF;
	private JTextField searchNTF;
	private JTextField searchTTF;

	JButton createButton, updateButton, deleteButton, cancelButton;
	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					LunchManageGUIApp frame = new LunchManageGUIApp();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public LunchManageGUIApp() {
		setResizable(false);
		setTitle("\uB9DB\uC9D1 \uAD00\uB9AC \uD504\uB85C\uADF8\uB7A8");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 782, 432);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);
		
		//JTable 
		String[] columnNames={"이름","전화번호","주소","거리","메모"};
		String[][] rowData={};
		
		DefaultTableModel tableModel=new DefaultTableModel(rowData, columnNames);
		
		table=new JTable(new DefaultTableModel(
			new Object[][] {
			},
			new String[] {
				"\uC774\uB984", "\uC804\uD654\uBC88\uD638", "\uC8FC\uC18C", "\uAC70\uB9AC", "\uBA54\uBAA8"
			}
		));
		table.setShowGrid(false);
		table.getTableHeader().setReorderingAllowed(false);
		table.getTableHeader().setResizingAllowed(false);
		
		// 테이블 내용 가운데 정렬하기
		DefaultTableCellRenderer dtcr = new DefaultTableCellRenderer(); // 디폴트테이블셀렌더러 생성 (가운데 정렬을 위한)
		// Renderer의 정렬을 가운데 정렬로 지정
		dtcr.setHorizontalAlignment(SwingConstants.CENTER);
		
		//정렬할 테이블의 ColumnModel을 가져옴 
		TableColumnModel tcm = table.getColumnModel();
		
		/*		 
		//반복문을 이용 전체 열에 지정
		for (int i = 0; i < tcm.getColumnCount(); i++) {
			tcm.getColumn(i).setCellRenderer(dtcr);
			}
		 */
		
		//특정 열에 지정
		tcm.getColumn(0).setCellRenderer(dtcr);  
		tcm.getColumn(1).setCellRenderer(dtcr);  
		tcm.getColumn(2).setCellRenderer(dtcr);  
	    tcm.getColumn(3).setCellRenderer(dtcr);
		//table.getColumnModel().getColumn(4).setMaxWidth(100);
		
		JScrollPane pane_table=new JScrollPane(table);
		pane_table.setSize(571, 252);
		pane_table.setLocation(206, 86);
		table.setBounds(200, 96, 554, 228);
		
		getContentPane().add(pane_table, BorderLayout.CENTER);
			
		JPanel panel_2 = new JPanel();
		panel_2.setBounds(6, 5, 755, 383);
		contentPane.add(panel_2);
		
		createButton = new JButton("\uC815\uBCF4 \uC800\uC7A5");
		createButton.setBounds(275, 15, 93, 36);
		createButton.setFont(new Font("굴림", Font.PLAIN, 13));
		panel_2.setLayout(null);
		panel_2.add(createButton);
		
		updateButton = new JButton("\uC815\uBCF4 \uBCC0\uACBD");
		updateButton.setBounds(380, 15, 93, 36);
		updateButton.setFont(new Font("굴림", Font.PLAIN, 13));
		panel_2.add(updateButton);
		
		deleteButton = new JButton("\uC815\uBCF4 \uC0AD\uC81C");
		deleteButton.setBounds(485, 15, 93, 36);
		deleteButton.setFont(new Font("굴림", Font.PLAIN, 13));
		panel_2.add(deleteButton);
		
		cancelButton = new JButton("맛집검색");
		cancelButton.setBounds(590, 15, 93, 36);
		cancelButton.setFont(new Font("굴림", Font.PLAIN, 13));
		panel_2.add(cancelButton);
		
		
		JPanel panel = new JPanel();
		panel.setLayout(null);
		panel.setBounds(0, 0, 201, 383);
		panel_2.add(panel);
		
		JLabel nameLabel = new JLabel("\uC774\uB984");
		nameLabel.setFont(new Font("굴림", Font.PLAIN, 11));
		nameLabel.setBounds(11, 30, 57, 15);
		panel.add(nameLabel);
		
		JLabel phoneLabel = new JLabel("\uC804\uD654\uBC88\uD638");
		phoneLabel.setFont(new Font("굴림", Font.PLAIN, 11));
		phoneLabel.setBounds(11, 65, 57, 15);
		panel.add(phoneLabel);
		
		JLabel addressLabel = new JLabel("\uC8FC\uC18C");
		addressLabel.setFont(new Font("굴림", Font.PLAIN, 11));
		addressLabel.setBounds(11, 100, 57, 15);
		panel.add(addressLabel);
		
		JLabel distanceLabel = new JLabel("\uAC70\uB9AC");
		distanceLabel.setFont(new Font("굴림", Font.PLAIN, 11));
		distanceLabel.setBounds(11, 135, 57, 15);
		panel.add(distanceLabel);
		
		JLabel memoLabel = new JLabel("\uBA54\uBAA8");
		memoLabel.setFont(new Font("굴림", Font.PLAIN, 11));
		memoLabel.setBounds(11, 170, 57, 15);
		panel.add(memoLabel);
		
		JLabel searchNTFLabel = new JLabel("\uC774\uB984 \uAC80\uC0C9");
		searchNTFLabel.setFont(new Font("굴림", Font.PLAIN, 11));
		searchNTFLabel.setBounds(11, 305, 57, 15);
		panel.add(searchNTFLabel);
		
		JLabel searchTTFLabel = new JLabel("\uAC70\uB9AC \uAC80\uC0C9");
		searchTTFLabel.setFont(new Font("굴림", Font.PLAIN, 11));
		searchTTFLabel.setBounds(11, 335, 57, 15);
		panel.add(searchTTFLabel);
		
		nameTF = new JTextField();
		nameTF.setColumns(10);
		nameTF.setBounds(62, 27, 116, 21);
		panel.add(nameTF);
		
		phoneTF = new JTextField();
		phoneTF.setColumns(10);
		phoneTF.setBounds(62, 62, 116, 21);
		panel.add(phoneTF);
		
		addressTF = new JTextField();
		addressTF.setColumns(10);
		addressTF.setBounds(62, 97, 116, 21);
		panel.add(addressTF);
		
		distanceTF = new JTextField();
		distanceTF.setColumns(10);
		distanceTF.setBounds(62, 132, 116, 21);
		panel.add(distanceTF);
		
		memoTF = new JTextField();
		memoTF.setColumns(10);
		memoTF.setBounds(62, 167, 116, 120);
		panel.add(memoTF);
		
		searchNTF = new JTextField();
		searchNTF.setColumns(10);
		searchNTF.setBounds(62, 302, 116, 21);
		panel.add(searchNTF);
		
		searchTTF = new JTextField();
		searchTTF.setColumns(10);
		searchTTF.setBounds(62, 332, 116, 21);
		
		panel.add(searchTTF);
		
		createButton.addActionListener(this);
		updateButton.addActionListener(this);
		deleteButton.addActionListener(this);
		cancelButton.addActionListener(this);
		
		displayAllLunchManage(0,null);
	}
	
	
	//테이블에 저장된 모든 정보를 검색하여 JTable 컴퍼넌트에 출력하는 메소드, 6월 21일-22일 
	public void displayAllLunchManage(int mode,String temp) {
		List<LunchManageDTO> lunchmanagerList=null;
		if(mode == 0) {
			lunchmanagerList=LunchManageDAO.getDAO().selectAllLunchManagerList();
		} else if(mode==1) {
			lunchmanagerList=LunchManageDAO.getDAO().selectNameManageList(temp);
		} else  if(mode==2) {
			lunchmanagerList=LunchManageDAO.getDAO().selectDistanceLunchManageList(temp);
		}
		
		if (lunchmanagerList.isEmpty()) {
			JOptionPane.showMessageDialog(this, "저장된 맛집정보가 없습니다.");
			return;
		}
		
		DefaultTableModel model=(DefaultTableModel)table.getModel(); 
		
		for (int i = model.getRowCount(); i >0; i--) {
			model.removeRow(0);
		}	
		//JTable 컴퍼넌트에 반환받은 학생정보를 출력 
		for(LunchManageDTO lunchmanage:lunchmanagerList) {
			Vector<Object> rowData=new Vector<Object>();
			rowData.add(lunchmanage.getName());
			rowData.add(lunchmanage.getPhone());
			rowData.add(lunchmanage.getAddress());
			rowData.add(lunchmanage.getDistance());
			rowData.add(lunchmanage.getMemo());
			model.addRow(rowData);
		}
	}
	
	//JTextField 컴퍼넌트로 입력된 학생정보를 제공받아 LUNCHMANAGE 테이블에 저장하는 메소드 - '정보 저장'
	public void createLunchManage() {
		String name=nameTF.getText(); 
		
		if (name.equals("")) { //입력값 없는 경우 
			JOptionPane.showMessageDialog(this, "이름을 반드시 입력해 주세요");
			nameTF.requestFocus();
			return;
		}
		
		String nameReg="[가-힣]{2,7}";//정규표현식
		if(!Pattern.matches(nameReg, name)) {
			JOptionPane.showMessageDialog(this, "이름은 2~5 범위의 한글만 입력해 주세요.");
			nameTF.requestFocus();
			return;
		}
		
		String phone=phoneTF.getText();
		
		if (phone.equals("")) {
			JOptionPane.showMessageDialog(this, "전화번호를 반드시 입력해 주세요");
			phoneTF.requestFocus();
			return;
		}
		
		String phoneReg="\\d{2,3}-\\d{3,4}-\\d{4}";
		if(!Pattern.matches(phoneReg, phone)) {
			JOptionPane.showMessageDialog(this, "전화번호를 형식에 맞게 입력해 주세요.");
			phoneTF.requestFocus();
			return;
		}
		
		String distance=distanceTF.getText();
		
		if (distance.equals("")) {
			JOptionPane.showMessageDialog(this, "거리를 반드시 입력해 주세요");
			distanceTF.requestFocus();
			return;
		}
		
		String address=addressTF.getText(); //유효성 검사 안해줘도 있어야 함 
		String memo=memoTF.getText();
		
		//컴퍼넌트 입력값으로 필드값 변경
		LunchManageDTO lunchmanage=new LunchManageDTO();
		lunchmanage.setName(name);
		lunchmanage.setPhone(phone);
		lunchmanage.setAddress(address);
		lunchmanage.setDistance(distance);
		lunchmanage.setMemo(memo);
		
		//정보를 전달하여 저장하기 위해 DAO 클래스 호출 
		int rows=LunchManageDAO.getDAO().insertLunchManage(lunchmanage);
		
		JOptionPane.showMessageDialog(this, rows+"개의 맛집 정보를 저장하였습니다.");
		
		displayAllLunchManage(0,null);
		//initDisplay();
		
	}
	
	//이름제공, 학생정보 삭제 - '정보 삭제'
	public void deleteLunchManage() {
		String name=nameTF.getText(); 
		
		if (name.equals("")) {
			JOptionPane.showMessageDialog(this, "이름을 반드시 입력해 주세요");
			nameTF.requestFocus();
			return;
		}
				
		int rows=LunchManageDAO.getDAO().deleteLunchManage(name);
		
		if(rows>0) {
			JOptionPane.showMessageDialog(this,rows+"개의 맛집정보를 삭제하였습니다.");
			displayAllLunchManage(0,null);
		} else {
			JOptionPane.showMessageDialog(this, "삭제하고자 하는 이름의 맛집정보가 없습니다.");
		}
		//initDisplay();
	}
		
	
	//학생정보 제공, 학생정보 변경 - '정보 변경'
	public void updateLunchManage() {
		//변경하기 위해서 modify
		//int no=Integer.parseInt(noTF.getText());
		
		String name=nameTF.getText();
		
		if(name.equals("")) {//입력값이 없는 경우
			JOptionPane.showMessageDialog(this, "이름을 반드시 입력해 주세요.");
			nameTF.requestFocus();//입력촛점을 이동하는 메소드
			return;
		}
		
		String nameReg="[가-힣]{2,7}";//정규표현식
		if(!Pattern.matches(nameReg, name)) {//정규표현식과 입력값의 형식이 다른 경우
			JOptionPane.showMessageDialog(this, "이름은 2~5 범위의 한글만 입력해 주세요.");
			nameTF.requestFocus();
			return;
		}
		
		String phone=phoneTF.getText();
		
		if(phone.equals("")) {//입력값이 없는 경우
			JOptionPane.showMessageDialog(this, "전화번호를 반드시 입력해 주세요.");
			phoneTF.requestFocus();//입력촛점을 이동하는 메소드
			return;
		}
		
		String phoneReg="\\d{2,3}-\\d{3,4}-\\d{4}"; //정규표현식
		if(!Pattern.matches(phoneReg, phone)) {//정규표현식과 입력값의 형식이 다른 경우
			JOptionPane.showMessageDialog(this, "전화번호를 형식에 맞게 입력해 주세요.");
			phoneTF.requestFocus();
			return;
		}
		
		String address=addressTF.getText();
		
		if(address.equals("")) {//입력값이 없는 경우
			JOptionPane.showMessageDialog(this, "주소를 반드시 입력해 주세요.");
			addressTF.requestFocus();//입력촛점을 이동하는 메소드
			return;
		}
		
		String distance=distanceTF.getText();
		
		if (distance.equals("")) {
			JOptionPane.showMessageDialog(this, "거리를 반드시 입력해 주세요");
			distanceTF.requestFocus();
			return;
		}
		
		String memo=memoTF.getText();
		
		//DTO 인스턴스를 생성하고 컴퍼넌트의 입력값으로 필드값 변경
		LunchManageDTO lunchmanage = new LunchManageDTO();
		lunchmanage.setName(name);
		lunchmanage.setPhone(phone);
		lunchmanage.setAddress(address);
		lunchmanage.setDistance(distance);
		lunchmanage.setMemo(memo);
		
		//학생정보를 전달하여 STUDENT 테이블에 저장된 기존 학생정보를 변경하는 DAO 클래스의
		//메소드 호출
		int rows=LunchManageDAO.getDAO().updateLunchManage(lunchmanage);
		
		JOptionPane.showMessageDialog(this, rows+"명의 학생정보를 변경 하였습니다.");
		
		displayAllLunchManage(0,null);
		//initDisplay();
	}
		
	@Override
	public void actionPerformed(ActionEvent ev) {
		// 메소드 호출 
		Component c = (Component) ev.getSource();
		if (c == createButton) {
			createLunchManage();
		} else if (c == deleteButton) {
			deleteLunchManage();
		} else if (c == updateButton ) {
			updateLunchManage();
		} else if (c == cancelButton) {
			String name=searchNTF.getText();
			String distance=searchTTF.getText();
			
			if(!name.equals("")) {
				searchNTF.setText("");
				displayAllLunchManage(1,name);

			} else if(!distance.equals("")) {
				searchTTF.setText("");
				displayAllLunchManage(2,distance);

			} else {
				displayAllLunchManage(0,null);
			}
		}	
	}
}
profile
배우는 초보개발자

0개의 댓글