Day27
2020. 11. 3. 14:38ㆍ교육과정/KOSMO
키워드 : 오토커밋 해제 / 계좌이체 (자바 오라클 연동) / 비디오샵 (버튼 작동) /
****
1. 잊지 말자 COMMIT
1) 오라클에서 생성하고 데이터까지 입력한 테이블에 관해서
2) 자바에서 화면 출력하고자 할 때
3) 오라클에서 COMMIT을 해두지 않으면 block 처리가 되는 바람에, 자바에서 출력이 되지 않는다.
★ 반드시 오라클에서 작업한 내용을 commit 해둔다!!
2. TabPane - 탭이 여러개 있는 패널 화면
3. 오토커밋 해제의 필요성
: 오토커밋으로 인한 문제상황을 방지하기 위해, SQL문 작성 및 전송작업 전에 오토커밋을 해제한다.
(+) 트랜잭션 : 하나의 작업세트, 작업단위를 트랜잭션이라고 한다.
<AccUI 클래스 소스 코드>
더보기
package jdbc.transection;
/******************************************************
* @ 트랙잭션 예제
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
public class AccUI implements ActionListener
{
//===================================================
// 프로그램 시작
public static void main(String[] args)
{
AccUI acc = new AccUI();
acc.setup();
acc.eventProc();
}
//===================================================
// 전역변수 선언
JFrame frame;
JButton b_moveMoney, b_cancel;
JTextField tf_sendAccNum, tf_recvAccNum, tf_moveMoney;
// 확인다이알로그에 필요한 변수 선언
JDialog confirmDia;
JLabel l_sendCust, l_recvCust, l_moveMoney, l_gainMoney;
JButton b_diaConfirm;
//===================================================
// 전역 변수의 객체 생성
public AccUI(){
frame = new JFrame("예금 이체 프로그램");
b_moveMoney = new JButton("예금이체실행");
b_cancel = new JButton("이체취소");
tf_sendAccNum = new JTextField(20);
tf_recvAccNum = new JTextField(20);
tf_moveMoney = new JTextField(20);
// 확인다이알로그에 필요한 변수 선언
confirmDia = new JDialog( frame, "이체결과확인");
l_sendCust = new JLabel();
l_recvCust = new JLabel();
l_moveMoney = new JLabel();
l_gainMoney = new JLabel();
b_diaConfirm = new JButton(" 정상처리되었습니다!!! ");
}
//===================================================
// 컴포넌트 붙이고 프레임 출력
public void setup(){
// 가운데 영역 ( 라벨과 텍스트필드 붙인 영역 )
JPanel p_center1 = new JPanel();
p_center1.setLayout( new FlowLayout(FlowLayout.RIGHT) );
p_center1.add( new JLabel("보내는분 계좌번호") );
p_center1.add( tf_sendAccNum );
JPanel p_center2 = new JPanel();
p_center2.setLayout( new FlowLayout(FlowLayout.RIGHT) );
p_center2.add( new JLabel("받는분 계좌번호") );
p_center2.add( tf_recvAccNum );
JPanel p_center3 = new JPanel();
p_center3.setLayout( new FlowLayout(FlowLayout.RIGHT) );
p_center3.add( new JLabel("이체 금액") );
p_center3.add( tf_moveMoney );
JPanel p_center = new JPanel();
p_center.setLayout( new GridLayout(3,1));
p_center.add( p_center1 );
p_center.add( p_center2 );
p_center.add( p_center3 );
// South 영역 ( 버튼 붙인 영역 )
JPanel p_south = new JPanel();
p_south.add( b_moveMoney );
p_south.add( b_cancel );
// 프레임에 붙이기
frame.getContentPane().setLayout( new BorderLayout(20,20));
frame.getContentPane().add("Center", p_center );
frame.getContentPane().add("South", p_south );
frame.pack();
frame.setVisible( true );
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
//---------------------------------------------------
// 다이알로그 붙이기
//---------------------------------------------------
l_sendCust.setBorder( new BevelBorder( BevelBorder.RAISED ));
l_recvCust.setBorder( new BevelBorder( BevelBorder.RAISED ));
l_moveMoney.setBorder( new BevelBorder( BevelBorder.RAISED ));
l_gainMoney.setBorder( new BevelBorder( BevelBorder.RAISED ));
JPanel p_diaCenter = new JPanel();
p_diaCenter.setLayout( new GridLayout(4, 2, 20, 20));
p_diaCenter.add( new JLabel(" 보내는 고객 "));
p_diaCenter.add( l_sendCust );
p_diaCenter.add( new JLabel(" 받 는 고 객"));
p_diaCenter.add( l_recvCust );
p_diaCenter.add( new JLabel(" 이 체 금 액 "));
p_diaCenter.add( l_moveMoney );
p_diaCenter.add( new JLabel(" 계좌남은금액 "));
p_diaCenter.add( l_gainMoney );
JPanel p_diaSouth = new JPanel();
p_diaSouth.add( b_diaConfirm );
confirmDia.getContentPane().setLayout( new BorderLayout(20,20));
confirmDia.getContentPane().add("Center", p_diaCenter);
confirmDia.getContentPane().add("South", p_diaSouth );
}
// 이벤트처리 할 컴포넌트를 등록
public void eventProc(){
b_moveMoney.addActionListener( this );
b_cancel.addActionListener( this );
}
// 액션 이벤트
public void actionPerformed( ActionEvent ev ){
Object o = ev.getSource();
// "이체실행" 버튼이 눌렸을 때
if ( o == b_moveMoney ) {
try{
////////////////////////////////////////////////////////
// 1. 화면에서 입력값 얻어오기
// 2. Business Logic 객체 생성 ( ex. AccLogic )
// 3. BL객체에서 계좌 이체하는 함수 호출 ( ex. moveAccount() )
// - 1번의 입력값을 인자로 넘김
// - 호출 후 넘겨받는 리턴값으로는 0이면 정상처리이고
// -1이면 잘못된 경우이므로 메세지박스 출력
// 화면의 "보내는 분 계좌번호" 입력창에서 얻어옴
String sendAcc = tf_sendAccNum.getText();
// 화면의 "받는 분 계좌번호" 입력창에서 얻어옴
String recvAcc = tf_recvAccNum.getText();
// 화면의 "이체 금액"에서 얻어옴
int mondy = Integer.parseInt(tf_moveMoney.getText());
/* AccLogic 클래스
생성자 함수에서는 오라클 드라이버를 등록한다.
클래스 내의 moveAccount() 메소드는
인자 3개를 받아서 계좌이체 작업을 수행한다. */
AccLogic logic = new AccLogic();
int result = logic.moveAccount(sendAcc, recvAcc, mondy); // logic에서 정의한 moveAccount메소드는 인자 3개를 받아서 처리한 뒤(계좌이체 작업)
// int값을 반환하므로 이를 받도록 int result 셋팅
if (result == -1)
JOptionPane.showMessageDialog(null, "이체실패");
/******************************************************
* 계좌 이체를 확인한 후에 결과를 다이알로그에 출력
1. BL객체에서 레코드 검색하는 함수호출 ( ex. confirmAccount() )
2. 1번의 결과로 받은 객체의 각각의 값을 다이알로그의 라벨에 출력
3. 다이알로그 화면 출력
*/
} catch(Exception ex){
System.out.println("이체처리시 : "+ ex.getMessage() );
JOptionPane.showMessageDialog
(frame,"이체하는 도중 에러가 발생하였습니다!! 이를 워쩌");
return;
}
}
// "이체취소" 버튼이 눌렸을 때
else if ( o == b_cancel)
{
frame.setVisible( false );
frame.dispose();
System.exit(0);
}
}
}
<AccLogic 클래스 소스 코드>
더보기
package jdbc.transection;
import java.sql.*;
public class AccLogic
{
// 연결 객체 생성시 필요한 변수 선언
String url;
String user;
String pass;
//===============================================
// 드라이버를 드라이버매니저에 등록
public AccLogic() throws Exception{
/////////////////////////////////////////////////////////
// 1. 드라이버를 드라이버 매니저에 등록
Class.forName("oracle.jdbc.driver.OracleDriver");
url = "jdbc:oracle:thin:@192.168.0.17:1521:orcl";
user = "scott";
pass = "tiger";
}
//====================================================
// 보내는 계좌번호와 받는 계좌번호와 계좌금액을 넘겨받아
// 보내는계좌에서 계좌금액을 빼고 받는계좌에서 계좌금액을 더한다
public int moveAccount(String sendAcc, String recvAcc, int amount) {
Connection con = null;
///////////////////////////////////////////////////////////
// 1. Connection 객체 생성
//@@ 2. Auto-commit을 해제
// 3. 출금계좌에서 이체금액을 뺀다
// 4. 입금계좌에 이체금액을 더한다
//@@ 5. commit을 전송한다
// 6. 객체 닫기
// - 만일 정상적인 경우는 0을 리턴하고 도중에 잘못되었으면
// 트랜잭션을 롤백시키고 -1을 리턴
// try문 안에 있는 모든 작업이 하나의 세트라고 볼 수 있다.
// 이러한 작업 단위를 트랜잭션이라고 한다.
try {
con = DriverManager.getConnection(url,user, pass); // 1.
con.setAutoCommit(false); // 2.
// --> 오토 커밋을 해제함으로써 도중에 문제가 발생하더라도 commit되지 않음
String sql1 = // 3.
"UPDATE account SET amount = amount - ? "
+ "WHERE account_num=?";
PreparedStatement ps1 = con.prepareStatement(sql1);
ps1.setInt (1, amount);
ps1.setString(2, sendAcc);
// 오라클로 SQL문을 보내고, 결과 수행값(n행 완료)을 알려준다.
int result1 = ps1.executeUpdate();
// 계좌가 없을 경우(0행 완료) 출금계좌에서는 인출되었으나 입금될 곳이 없는 상태임
if (result1 == 0) {
con.rollback();
return -1;
// --> AccUI클래스의 moveAccount()를 호출한 곳에 -1을 리턴하고
// "이체 실패" 메세지가 출력되도록 한다.
}
String sql2 = // 4.
"UPDATE account SET amount = amount + ? "
+ "WHERE account_num=?";
PreparedStatement ps2 = con.prepareStatement(sql2);
ps2.setInt (1, amount);
ps2.setString(2, recvAcc);
int result2 = ps2.executeUpdate();
if (result2 == 0) {
con.rollback();
return -1;
}
con.commit(); // 5.
}catch (Exception ex) {
try { con.rollback(); } catch(Exception e) {}
return -1; // try에서 하는 작업이 실패할 경우 -1 리턴
}finally {
try { con.close(); } catch(Exception ex) {} // 6.
}
return 0;
}
//=======================================================
// 보내는계좌번호와 받는계좌번호를 넘겨받아
// 보내는계좌고객명과 보내는계좌의남은 금액을 얻어오고
// 받는계좌고객명을 얻어와서
// 얻은 정보를 ConfirmData객체에 넣고 리턴
public ConfirmData confirmAccount(String sendAcc, String recvAcc)
throws Exception{
String sendCust="", recvCust="";
int gainMoney=0;
ConfirmData resultData=null;
// 1. Connection 객체 생성
// 2. 테이블에서, 넘겨받은 sendAcc와 같은 account_num필드에서
// customer, amount를 얻어온다
// 3. 테이블에서, 넘겨받은 recvAcc와 같은 account_num필드에서
// customer를 얻어온다
// 4. 2와 3에서 얻은 값을 ConfirmData 객체에 저장
// 5. 4번의 객체를 리턴
return resultData;
}
}
//#################################################################
// 테이블명 : account
// account_num 계좌번호 varchar2(20)
// customer 고객명 varchar2(20)
// amount 계좌금액 int
<ConfirmData 클래스 소스 코드>
더보기
package jdbc.transection;
public class ConfirmData
{
String sendCust;
String recvCust;
int gainMoney;
public ConfirmData() {
}
public void setSendCust( String sendCust ){
this.sendCust = sendCust;
}
public String getSendCust() {
return sendCust;
}
public void setRecvCust( String recvCust ){
this.recvCust = recvCust;
}
public String getRecvCust() {
return recvCust;
}
public void setGainMoney( int gainMoney ){
this.gainMoney = gainMoney;
}
public int getGainMoney() {
return gainMoney;
}
}
4. 비디오샵
(1) 회원가입 버튼 작동 관련 메소드
(2) 번호검색 버튼 작동 관련 메소드
(3) 회원수정 버튼 작동 관련 메소드
(4) 이름검색 버튼 작동 관련 메소드
<CustomerView 클래스 소스 코드>
더보기
package videoshop.view;
import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import videoshop.model.CustomerDAO;
import videoshop.model.vo.CustomerVO;
public class CustomerView extends JPanel implements ActionListener
{
JFrame frm;
JTextField tfCustName, tfCustTel, tfCustTelAid, tfCustAddr, tfCustEmail;
JButton bCustRegist, bCustModify;
JTextField tfCustNameSearch, tfCustTelSearch;
JButton bCustNameSearch, bCustTelSearch;
// 모델단 - 비지니스 로직
CustomerDAO dao;
// 회원번호가 있을 경우에만
// int memberId;
public CustomerView(){
addLayout();
eventProc();
try {
dao = new CustomerDAO();
System.out.println("DB 연결성공");
} catch (Exception e) {
System.out.println("DB 연결실패:" + e.toString());
e.printStackTrace();
}
}
public void eventProc() {
bCustRegist.addActionListener(this);
bCustModify.addActionListener(this);
bCustNameSearch.addActionListener(this);
bCustTelSearch.addActionListener(this);
}
public void actionPerformed(ActionEvent ev) {
Object evt = ev.getSource();
if (evt == bCustRegist) { // 회원가입
insertCustomer();
}else if (evt == bCustModify) { // 수정버튼이 눌렸을 때
modifyCustomer();
}else if (evt == bCustTelSearch) { // 전화번호로 검색
searchByTel();
}else if (evt == bCustNameSearch) { // 이름으로 검색
searchByName();
}
}
/**
* 함수명 : insertCustomer()
* 인자 : 없음
* 리턴값 : void
* 역할 : 회원가입을 위해 사용자 입력값을 받아서 모델로 전달
*/
void insertCustomer() {
// 1. 화면 입력값 얻어오기
// 2. VO 객체의 멤버 변수로 화면의 입려값들을 저장
// 3. 모델단의 regist() 호출
CustomerVO vo = new CustomerVO(); // 1.
vo.setCustName(tfCustName.getText()); // 2.
vo.setCustTel(tfCustTel.getText());
vo.setCustAddr(tfCustAddr.getText());
vo.setCustmail(tfCustEmail.getText());
vo.setCustSubTel(tfCustTelAid.getText());
try {
dao.regist(vo); // 3. 회원가입 메소드
clearTextFields();
}catch (Exception e) {
System.out.println("입력 실패: " + e.toString());
}
}
/**
* 함수명 : clearTextFields()
* 인자 : 없음
* 리턴값 : 없음
* 역할 : 입력창 클리어
*/
void clearTextFields() {
tfCustName .setText(null);
tfCustTel .setText(null);
tfCustAddr .setText(null);
tfCustEmail .setText(null);
tfCustTelAid.setText(null);
}
/**
* 함수명 : searchByTel()
* 인자 : 없음
* 리턴값 : void
* 역할 : 전화번호로 검색시 고객 정보 불러와서 화면에 출력
*/
void searchByTel() {
String tel = tfCustTelSearch.getText();
try {
CustomerVO vo = dao.searchTel(tel);
// memberId = be.getCustNo();
tfCustName .setText(vo.getCustName());
tfCustTel .setText(vo.getCustTel());
tfCustTelAid.setText(vo.getCustSubTel());
tfCustAddr .setText(vo.getCustAddr());
tfCustEmail .setText(vo.getCustmail());
} catch (Exception e) {
System.out.println("전화번호 검색 실패: " + e.toString());
e.printStackTrace();
}
}
/**
* 함수명 : modifyCustomer()
* 인자 : 없음
* 리턴값 : void
* 역할 : 수정버튼 눌렸을 때 Tel을 제외한 DB의 회원정보를 수정
*/
void modifyCustomer() {
CustomerVO vo = new CustomerVO();
vo.setCustTel (tfCustTel .getText());
vo.setCustName (tfCustName .getText());
vo.setCustAddr (tfCustAddr .getText());
vo.setCustSubTel(tfCustTelAid.getText());
vo.setCustmail (tfCustEmail .getText());
try {
dao.modify(vo);
clearTextFields();
}catch (Exception e) {
System.out.println("수정실패: " + e.toString());
}
}
void searchByName() {
String name = tfCustNameSearch.getText();
try {
ArrayList list = dao.searchName(name);
for (int i=0; i<list.size(); i++) {
CustomerVO vo = (CustomerVO)list.get(i);
tfCustName .setText(vo.getCustName());
tfCustTel .setText(vo.getCustTel());
tfCustTelAid.setText(vo.getCustSubTel());
tfCustAddr .setText(vo.getCustAddr());
tfCustEmail .setText(vo.getCustmail());
}
} catch (Exception e) {
System.out.println("검색실패:" + e.toString());
}
}
/* 화면구성 */
public void addLayout()
{
tfCustName = new JTextField(20);
tfCustTel = new JTextField(20);
tfCustTelAid = new JTextField(20);
tfCustAddr = new JTextField(20);
tfCustEmail = new JTextField(20);
tfCustNameSearch = new JTextField(20);
tfCustTelSearch = new JTextField(20);
bCustRegist = new JButton("회원가입");
bCustModify = new JButton("회원수정");
bCustNameSearch = new JButton("이름검색");
bCustTelSearch = new JButton("번호검색");
// 회원가입 부분 붙이기
// ( 그 복잡하다던 GridBagLayout을 사용해서 복잡해 보임..다른 쉬운것으로...대치 가능 )
JPanel pRegist = new JPanel();
pRegist.setLayout( new GridBagLayout() );
GridBagConstraints cbc = new GridBagConstraints();
cbc.weightx = 1.0;
cbc.weighty = 1.0;
cbc.fill = GridBagConstraints.BOTH;
cbc.gridx = 0; cbc.gridy = 0; cbc.gridwidth = 1; cbc.gridheight= 1;
pRegist.add( new JLabel(" 이 름 ") , cbc );
cbc.gridx = 1; cbc.gridy = 0; cbc.gridwidth = 1; cbc.gridheight= 1;
pRegist.add( tfCustName , cbc );
cbc.gridx = 2; cbc.gridy = 0; cbc.gridwidth = 1; cbc.gridheight= 1;
pRegist.add( bCustModify, cbc );
cbc.gridx = 3; cbc.gridy = 0; cbc.gridwidth = 1; cbc.gridheight= 1;
pRegist.add( bCustRegist, cbc );
cbc.gridx = 0; cbc.gridy = 1; cbc.gridwidth = 1; cbc.gridheight= 1;
pRegist.add( new JLabel(" 전 화 ") , cbc );
cbc.gridx = 1; cbc.gridy = 1; cbc.gridwidth = 1; cbc.gridheight= 1;
pRegist.add( tfCustTel , cbc );
cbc.gridx = 2; cbc.gridy = 1; cbc.gridwidth = 1; cbc.gridheight= 1;
pRegist.add( new JLabel(" 추가전화 ") , cbc );
cbc.gridx = 3; cbc.gridy = 1; cbc.gridwidth = 1; cbc.gridheight= 1;
pRegist.add( tfCustTelAid , cbc );
cbc.gridx = 0; cbc.gridy = 2; cbc.gridwidth = 1; cbc.gridheight= 1;
pRegist.add( new JLabel(" 주 소 ") , cbc );
cbc.gridx = 1; cbc.gridy = 2; cbc.gridwidth = 3; cbc.gridheight= 1;
pRegist.add( tfCustAddr , cbc );
cbc.gridx = 0; cbc.gridy = 3; cbc.gridwidth = 1; cbc.gridheight= 1;
pRegist.add( new JLabel(" 이메일 ") , cbc );
cbc.gridx = 1; cbc.gridy = 3; cbc.gridwidth = 3; cbc.gridheight= 1;
pRegist.add( tfCustEmail , cbc );
// 회원검색 부분 붙이기
JPanel pSearch = new JPanel();
pSearch.setLayout( new GridLayout(2, 1) );
JPanel pSearchName = new JPanel();
pSearchName.add( new JLabel(" 이 름 "));
pSearchName.add( tfCustNameSearch );
pSearchName.add( bCustNameSearch );
JPanel pSearchTel = new JPanel();
pSearchTel.add( new JLabel(" 전화번호 "));
pSearchTel.add( tfCustTelSearch );
pSearchTel.add( bCustTelSearch );
pSearch.add( pSearchName );
pSearch.add( pSearchTel );
// 전체 패널에 붙이기
setLayout( new BorderLayout() );
add("Center", pRegist );
add("South", pSearch );
}
}
<CustomerDAO 클래스 소스 코드>
더보기
package videoshop.model;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import videoshop.model.vo.CustomerVO;
public class CustomerDAO
{
// constructor
public CustomerDAO() throws Exception{
connectDB();
}
//###########################################################
// DB control method
Connection con;
String url = "jdbc:oracle:thin:@192.168.0.17:1521:orcl";
String user = "scott";
String pass = "tiger";
void connectDB() throws Exception {
/*
1. 드라이버를 드라이버메니저에 등록
2. 연결 객체 얻어오기
*/
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection(url,user, pass);
}
public void regist( CustomerVO cust ) throws Exception {
/*
1. sql 작성하기 ( insert 문 작성 : CustomerVO의 멤버변수로 각각 지정)
2. sql 전송객체 얻어오기( PreparedStatement가 더 적합할 듯 )
3. sql 전송 ( 전송전에 ?로 지정 )
4. 닫기 ( Connection은 닫으면 안됨 )
*/
PreparedStatement ps=null; // 2-1.
try {
String sql = "INSERT INTO member " // 1.
+ "(tel, name, sub_tel, addr, email) "
+ "VALUES (?, ?, ?, ?, ?)";
ps = con.prepareStatement(sql); // 2-2.
ps.setString(1, cust.getCustTel());
ps.setString(2, cust.getCustName());
ps.setString(3, cust.getCustSubTel());
ps.setString(4, cust.getCustAddr());
ps.setString(5, cust.getCustmail());
int result = ps.executeUpdate(); // 3.
System.out.println(result+"행을 입력");
}finally {
try { ps.close(); } catch(Exception e) {} // 4
}
}
public void modify( CustomerVO cust) throws Exception{
/*
1. sql 작성하기 ( update 문 작성 : CustomerVO의 멤버변수로 각각 지정)
2. sql 전송객체 얻어오기( PreparedStatement가 더 적합할 듯 )
3. sql 전송 ( 전송전에 ?로 지정 )
4. 닫기 ( Connection은 닫으면 안됨 )
*/
PreparedStatement ps=null; // 2-1.
try {
String sql = "UPDATE member SET " // 1.
+ "name=?, sub_tel=?, addr=?, email=? "
+ "WHERE tel=?";
ps = con.prepareStatement(sql); // 2-2.
ps.setString(1, cust.getCustName());
ps.setString(2, cust.getCustSubTel());
ps.setString(3, cust.getCustAddr());
ps.setString(4, cust.getCustmail());
ps.setString(5, cust.getCustTel());
int result = ps.executeUpdate(); // 3.
System.out.println(result+"행을 입력");
}finally {
try { ps.close(); } catch(Exception e) {} // 4.
}
}
public ArrayList searchName( String name ) throws Exception {
/*
1. sql 작성하기 ( select 문
: 함수의 인자로 넘어온 이름과 같은 조건의 레코드 검색 )
2. sql 전송객체 얻어오기( Statement / PreparedStatement 모두 적합 )
3. sql 전송 ( ResultSet 의 데이타를 얻어서 멤버 필드에 지정 )
4. 닫기 ( Connection은 닫으면 안됨 )
# 생각해 보기
- 동명 이인이 여러명 인 경우는 어떻게 처리할까?
*/
ArrayList list = new ArrayList();
PreparedStatement ps = null; // 2-1.
try {
String sql = // 1.
"SELECT * FROM member WHERE name = ?";
ps = con.prepareStatement(sql); // 2-2.
ps.setString(1, name);
ResultSet rs = ps.executeQuery(); // 3.
System.out.println(rs);
if (rs.next()) {
CustomerVO vo = new CustomerVO();
vo.setCustName (rs.getString("NAME"));
vo.setCustTel (rs.getString("TEL"));
vo.setCustSubTel(rs.getString("SUB_TEL"));
vo.setCustAddr (rs.getString("ADDR"));
vo.setCustmail (rs.getString("EMAIL"));
list.add(vo);
}
} finally {
try { ps.close(); } catch(Exception e) {} // 4.
}
return list;
}
public CustomerVO searchTel( String tel ) throws Exception {
/*
1. sql 작성하기 ( select 문
: 함수의 인자로 넘어온 전화번호과 같은 조건의 레코드 검색 )
2. sql 전송객체 얻어오기( Statement / PreparedStatement 모두 적합 )
3. sql 전송 ( ResultSet 의 데이타를 얻어서 멤버 필드에 지정 )
결과집합의 컬럼값을 CustomerVO의 각각 멤버 지정
4. 닫기 ( Connection은 닫으면 안됨 )
*/
CustomerVO vo = new CustomerVO();
PreparedStatement ps = null; // 2-1.
try {
String sql = // 1.
"SELECT * FROM member WHERE tel = ?";
ps = con.prepareStatement(sql); // 2-2.
ps.setString(1, tel);
ResultSet rs = ps.executeQuery(); // 3.
if (rs.next()) {
vo.setCustName(rs.getString("NAME"));
vo.setCustTel(rs.getString("TEL"));
vo.setCustSubTel(rs.getString("SUB_TEL"));
vo.setCustAddr(rs.getString("ADDR"));
vo.setCustmail(rs.getString("EMAIL"));
}
}finally {
try { ps.close(); } catch(Exception e) {} // 4.
}
return vo;
}
}
<VideoShop 클래스 소스 코드>
더보기
package videoshop;
import java.awt.*;
import javax.swing.*;
import videoshop.view.CustomerView;
import videoshop.view.RentView;
import videoshop.view.VideoView;
public class VideoShop extends JFrame
{
CustomerView customer;
VideoView video;
RentView rent;
public VideoShop(){
//������ ȭ���� �����ϴ� Ŭ���� ��ü ����
customer = new CustomerView();
video = new VideoView();
rent = new RentView();
JTabbedPane pane = new JTabbedPane();
pane.addTab("고객관리", customer );
pane.addTab("비디오관리", video);
pane.addTab("대여관리", rent );
pane.setSelectedIndex(2);
getContentPane().add("Center", pane );
pack();
setVisible( true );
setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
public static void main(String[] args)
{
new VideoShop();
}
}
<CustomerVO 클래스 소스 코드>
더보기
package videoshop.model.vo;
public class CustomerVO {
String custTel;
String custName;
String custSubTel;
String custAddr;
String custmail;
// constructor
public CustomerVO() {
super();
}
// setter, getter
public String getCustTel() {
return custTel;
}
public void setCustTel(String custTel) {
this.custTel = custTel;
}
public String getCustName() {
return custName;
}
public void setCustName(String custName) {
this.custName = custName;
}
public String getCustSubTel() {
return custSubTel;
}
public void setCustSubTel(String custSubTel) {
this.custSubTel = custSubTel;
}
public String getCustAddr() {
return custAddr;
}
public void setCustAddr(String custAddr) {
this.custAddr = custAddr;
}
public String getCustmail() {
return custmail;
}
public void setCustmail(String custmail) {
this.custmail = custmail;
}
}
<RentView 클래스 소스 코드>
더보기
package videoshop.view;
import java.awt.Color;
import javax.swing.JPanel;
public class RentView extends JPanel
{
public RentView(){
setBackground( Color.yellow );
}
}
<VideoView 클래스 소스 코드>
더보기
package videoshop.view;
import java.awt.Color;
import javax.swing.JPanel;
public class RentView extends JPanel
{
public RentView(){
setBackground( Color.yellow );
}
}
반응형