관리 메뉴

JIHYUN JEONG

[JAVA] SWING을 이용한 오라클 DB 테이블 만들기_08 본문

Information Technology/Java

[JAVA] SWING을 이용한 오라클 DB 테이블 만들기_08

StopHyun 2013. 2. 27. 19:12

자바(JAVA) SWING을 이용하여 and (JDBC) 오라클 DB 테이블 만들기 입니다.


[ 결과 화면] 


1 번



2번





3번



4번





[ 소스코드 ]



package asianaidt.prac;


import java.awt.*;

import java.awt.event.*;

import java.util.Vector;

import javax.swing.*;

import javax.swing.table.*;


public class VectorTableModel extends JFrame {

Vector outer, in,in2,in3, title;

JTable table;

DefaultTableModel model;


    public VectorTableModel() {//화면생성하고 listener등록

        super("TableDemo");

outer = new Vector();

in = new Vector();

in2 = new Vector();

in3 = new Vector();


in.add("111");

in.add("diane soyer");

in.add("seattle");


in2.add("222");

in2.add("tommy");

in2.add("la");


in3.add("333");

in3.add("billy");

in3.add("seoul");


title = new Vector();

title.add("num");

title.add("name");

title.add("address");

outer.add(in);

outer.add(in2);

outer.add(in3);

       

  model =  new DefaultTableModel();

       table = new JTable(model);

       

  model.setDataVector(outer, title);


  JScrollPane scrollPane = new JScrollPane(table);


Container c  = getContentPane();


c.add(new JLabel("TableDemo",JLabel.CENTER), "North");

c.add(scrollPane, BorderLayout.CENTER);

  

        

}


public static void main(String[] args) {

        VectorTableModel frame = new VectorTableModel();

        frame.pack();

        frame.setVisible(true);

}


 

   }







package asianaidt.prac;


import javax.swing.*;

import javax.swing.table.*;

import java.awt.*;

import java.awt.event.WindowAdapter;

import java.awt.event.WindowEvent;

import java.util.Vector;

import java.sql.*;


public class JdbcVectorTable extends JFrame {

Vector<Vector> out;

Vector<String> in, title;


// DB 작업 관련 변수...

String connect = "jdbc:oracle:thin:@127.0.0.1:1521:xe"; // loop back address

// : 로컬PC(여기서는

// 127.0.0.1)

// String connect = "jdbc:oracle:thin:@localhost:1521:dada"; // localhost로

// 써도 무방하다

String user = "scott";

String passwd = "tiger";


Connection conn;

Statement stat;


public JdbcVectorTable() {

super("TableDemo");


title = new Vector<String>();

out = new Vector<Vector>();


title.add("num");

title.add("name");

title.add("address");


getData();


JTable table = new JTable(out, title);

JScrollPane scrollPane = new JScrollPane(table);

Container c = getContentPane(); // 내용이 들어가는 판


c.add(scrollPane, BorderLayout.CENTER);

setDefaultCloseOperation(EXIT_ON_CLOSE);


addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent w) {

try {

stat.close();

conn.close();


setVisible(false); // 화면에 보이지 않게 하기

dispose(); // 화면 띄우는데 사용했던 자원 반납

System.exit(0); // 프로세스 종료

} catch (Exception e) {


}

}

});


pack();

setVisible(true);


}


// DB에서 데이터를 가져와서 out 벡터에 넣어주기

public void getData() {

// 1~6


// 1.driver 등록

try {

Class.forName("oracle.jdbc.driver.OracleDriver");


// 2.connection 얻기 (네트워크 연결)

conn = DriverManager.getConnection(connect, user, passwd);


// 3. statement 얻기

stat = conn.createStatement();


String query = "select * from customer";


// 4.query 실행 후 결과 집합 얻기

ResultSet rs = stat.executeQuery("select * from customer");


ResultSetMetaData rsmd = rs.getMetaData();


// 5.결과집합 처리


// JdbcVectorTable 설명 듣기

while (rs.next()) {

in = new Vector<String>();

for (int i = 1; i <= rsmd.getColumnCount(); i++) {

in.add(rs.getString(i));


}

out.add(in);

}


} catch (Exception e) {


e.printStackTrace();

}


}


public static void main(String[] args) {

JdbcVectorTable frame = new JdbcVectorTable();


}

}






package asianaidt.prac;


import java.awt.BorderLayout;

import java.awt.Container;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.awt.event.MouseAdapter;

import java.awt.event.MouseEvent;

import java.awt.event.WindowAdapter;

import java.awt.event.WindowEvent;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.Statement;

import java.util.Vector;


import javax.swing.JButton;

import javax.swing.JFrame;

import javax.swing.JLabel;

import javax.swing.JPanel;

import javax.swing.JScrollPane;

import javax.swing.JTable;

import javax.swing.JTextField;

import javax.swing.table.DefaultTableModel;


public class JdbcVectorTableEvent extends JFrame implements ActionListener {

Vector out, title;

JTable table;

DefaultTableModel model;

JButton add, del, update, clear;

JTextField tnum, tname, taddress;

JLabel lnum, lname, laddress;


// DB 관련 변수

String connect = "jdbc:oracle:thin:@127.0.0.1:1521:xe"; // loop back address

// : 로컬PC(여기서는

// 127.0.0.1)

// String connect = "jdbc:oracle:thin:@localhost:1521:dada"; // localhost로

// 써도 무방하다

String user = "scott";

String passwd = "tiger";


Connection con;

Statement stat;

PreparedStatement pin, pdel, pup;


public JdbcVectorTableEvent() {// 화면생성하고 listener등록

super("TableDemo");

prepareDB(); // 준비작업을 시킨다.


out = new Vector();

title = new Vector();

title.add("num");

title.add("name");

title.add("address");


model = new DefaultTableModel();

table = new JTable(model);


JScrollPane scrollPane = new JScrollPane(table);


Vector result = selectAll();

model.setDataVector(result, title); // 테이블 그릴때 쓰는 함수, result는 2차원 함수


table.addMouseListener(new MouseAdapter() { // 무명 클래스

public void mouseClicked(MouseEvent m) {


// 클릭한 행의 인덱스 알아내기-->JTable의 메소드

int index = table.getSelectedRow();

// 인덱스 이용해서 out안의 작은 벡터 in 꺼내기

Vector in = (Vector)out.get(index); // 형 변환 시켜줘야함

// in 안에 들어 있는 번호,이름,주소 알아내서 텍스트 필드에 넣어주기

String num = (String)in.get(0);

String name = (String)in.get(1);

String address = (String)in.get(2);

tnum.setText(num);

tname.setText(name);

taddress.setText(address);

// 번호가 들어가는 텍스트 필드는 편집 불가 상태로 변경

tnum.setEditable(false);

// tname.setEditable(false);

// taddress.setEditable(false);

}

});


JPanel panel = new JPanel();

tnum = new JTextField(8);

tname = new JTextField(10);

taddress = new JTextField(8);


lnum = new JLabel("num");

lname = new JLabel("name");

laddress = new JLabel("address");


add = new JButton("add");

del = new JButton("del");

update = new JButton("update");

clear = new JButton("clear");


add.addActionListener(this);

del.addActionListener(this);

update.addActionListener(this);

clear.addActionListener(this);


panel.add(lnum);

panel.add(tnum);

panel.add(lname);

panel.add(tname);

panel.add(laddress);

panel.add(taddress);


panel.add(add);

panel.add(del);

panel.add(update);

panel.add(clear);


Container c = getContentPane();


c.add(new JLabel("TableDemo", JLabel.CENTER), "North");

c.add(scrollPane, BorderLayout.CENTER);

c.add(panel, BorderLayout.SOUTH);


addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent w) {

try {

stat.close();

con.close();


setVisible(false); // 화면에 보이지 않게 하기

dispose(); // 화면 띄우는데 사용했던 자원 반납

System.exit(0); // 프로세스 종료

} catch (Exception e) {


}

}

});

}


public static void main(String[] args) {

JdbcVectorTableEvent frame = new JdbcVectorTableEvent();

frame.pack();

frame.setVisible(true);

}


// db 준비작업:드라이버 등록, Connection, Statement, PreparedStatement 만들기

public void prepareDB() {

try {

Class.forName("oracle.jdbc.driver.OracleDriver");

con = DriverManager.getConnection(connect, user, passwd);

stat = con.createStatement(); // select 때 사용

pin = con.prepareStatement("insert into customer values(?,?,?)");

pdel = con.prepareStatement("delete customer where num = ?");

pup = con

.prepareStatement("update customer set name = ?, address =? where num = ?");


} catch (Exception e) {

}


}


// db에서 데이터 가져와서 out에 넣은 후에 return해 줌

public Vector selectAll() {

out.clear();

try {

ResultSet rs = stat

.executeQuery("select * from customer order by num");


while (rs.next()) {

Vector in = new Vector<String>();

String num = rs.getString(1); // 1, 2,3 은 인덱스

// String num = rs.getString("num"); // 컬럼(num) 으로 줘도 무방하다

String name = rs.getString(2);

String address = rs.getString(3);

in.add(num);

in.add(name);

in.add(address);


// Vector result = selectAll();

// model.setDataVector(result, title); // 테이블 그릴때 쓰는 함수, result는 2차원 함수

out.add(in);

}

} catch (Exception e) {


}

return out;

}


// 이벤트 처리

public void actionPerformed(ActionEvent e) {

Object o = e.getSource();// 이벤트 발생 대상 알아내기


if (o != clear) { // clear 칸안에 있던 글자만 지우는 역활

if (o == add) { // db에 insert

String num = tnum.getText();

String name = tname.getText();

String address = taddress.getText();

insert(num, name, address);

}

if (o == del) { // db에서 delete

String num = tnum.getText();

delete(num);


}

if (o == update) {// 수정

String num = tnum.getText();

String address = taddress.getText();

String name = tname.getText();

update(name, address, num);


}


// 화면에 JTable 다시 그리기

Vector result = selectAll();

model.setDataVector(result, title); // 테이블 그릴때 쓰는 함수, result는 2차원 함수


}


tnum.setText("");

tname.setText("");

taddress.setText("");


tnum.setEditable(true); // setEditable 편집가능 하게

}


private void update(String name, String address, String num) {

try {

pup.setString(1, name);

pup.setString(2, address);

pup.setString(3, num);

pup.executeUpdate();

} catch (Exception e) {

}

}


private void delete(String num) {

try {

pdel.setString(1, num);

pdel.executeUpdate();

} catch (Exception e) {}

}


private void insert(String num, String name, String address) {

try {

pin.setString(1, num);

pin.setString(2, name);

pin.setString(3, address);

pin.executeUpdate();

} catch (Exception e) {}

}

}






package asianaidt.addressBook;


import java.sql.*;


import javax.swing.*;


import java.awt.*;

import java.util.*;


import javax.swing.table.*; 


import java.awt.event.*;


public class AddressBook extends JFrame implements ActionListener {


JLabel label,id, name, phone,address,company;

JTextField fid,fname,fphone,faddress,fcompany,search;

JButton add,delete,update,clear,all,sbutton;

String items[] = {"이름","주소","회사"};

JComboBox combo;

JPanel bottompanel,leftpanel,center,pid,pname,pphone,padd,pcom;


JScrollPane sp;

Vector outer,title, noresult, msg ; //noresult :검색결과없을때 테이블때문에

JTable table;

DefaultTableModel model;


String connect = new String("jdbc:oracle:thin:@localhost:1521:xe");

String user = new String("scott");

String passwd = new String("tiger");


Connection conn;

Statement stat;

PreparedStatement prestat1, prestat2, prestat3;

ResultSet rs;


public AddressBook(){

makeGui(); //화면구성

prepareDB(); //db 준비작업

select(null); //첫화면에서 테이블의 모든 내용보여주기 위해 select하는 함수

model.setDataVector(outer, title);

}


public void makeGui(){


label = new JLabel("Address Book",JLabel.CENTER);

id = new JLabel("   I D :  ",JLabel.CENTER);


fid = new JTextField(15);

pid = new JPanel();

pid.add(id);

pid.add(fid);


name = new JLabel("이름 : ");

fname = new JTextField(15);

pname = new JPanel();

pname.add(name);

pname.add(fname);


phone = new JLabel("전화 : ");

fphone = new JTextField(15);

pphone = new JPanel();

pphone.add(phone);

pphone.add(fphone);


address = new JLabel("주소 : ");

faddress = new JTextField(15);

padd = new JPanel();

padd.add(address);

padd.add(faddress);


company = new JLabel("회사 : ");

fcompany = new JTextField(15);

pcom = new JPanel();

pcom.add(company);

pcom.add(fcompany);

leftpanel = new JPanel();

leftpanel.setLayout(new GridLayout(5,1));

leftpanel.add(pid);

leftpanel.add(pname);

leftpanel.add(pphone);

leftpanel.add(padd);

leftpanel.add(pcom);


add = new JButton("추가");

add.addActionListener(this);

delete = new JButton("삭제");

delete.addActionListener(this);

update = new JButton("수정");

update.addActionListener(this);


combo = new JComboBox(items);

search = new JTextField(15);

search.addActionListener(this);


sbutton = new JButton("검색");

sbutton.addActionListener(this);


clear = new JButton("지우기");

clear.addActionListener(this);

all = new JButton("전체보기");

all.addActionListener(this);

bottompanel = new JPanel();

bottompanel.add(add);

bottompanel.add(delete);

bottompanel.add(update);

bottompanel.add(combo);

bottompanel.add(search);

bottompanel.add(sbutton);

bottompanel.add(clear);

bottompanel.add(all);

title = new Vector();

outer = new Vector();

noresult = new Vector();

msg = new Vector();


title.add("ID");

title.add("Name");

title.add("Phone");

title.add("Address");

title.add("Company");


noresult.add("실행 결과");


addWindowListener(new WindowAdapter(){

@Override

public void windowClosing(WindowEvent w) {

try {

rs.close();

stat.close();

conn.close();

setVisible(false);

dispose();

System.exit(0);

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

super.windowClosing(w);

}

});


Container c = getContentPane();

// DefaultTableModel 생성

model = new DefaultTableModel();

//model 사용해서 JTable 생성

table = new JTable(model);

table.addMouseListener(new MouseAdapter(){

public void mouseClicked(MouseEvent me){

//클릭한 행의 인덱스 알아내기-->JTable의 메소드

  int index = table.getSelectedRow();

 

  

 //인덱스 이용해서 out안의 작은 벡터 in 꺼내기

  Vector msg = (Vector) outer.get(index);

  

 //in 안에 들어 있는 번호,이름,주소 알아내서 텍스트 필드에 넣어주기

  String id = (String) msg.get(0);

  String name = (String) msg.get(1);

  String phone = (String) msg.get(2);

  String address = (String) msg.get(2);

  String company = (String) msg.get(2);

  

  

  fid.setText(id);

  fname.setText(name);

  fphone.setText(phone);

  faddress.setText(address);

  fcompany.setText(company);

  

 //번호가 들어가는 텍스트 필드는 편집 불가 상태로 변경

  fid.setEditable(false);

}

});


sp = new JScrollPane(table);


center = new JPanel();

center.add(leftpanel);

center.add(sp);


c.add(label,"North");

c.add(center,"Center");

c.add(bottompanel,"South");

}

public void prepareDB(){


//Statement

//PreparedStatement

try {

//driver 등록

Class.forName("oracle.jdbc.driver.OracleDriver"); //객체 생성

//connection 얻기

conn = DriverManager.getConnection(connect, user, passwd);

//statement 얻기

stat = conn.createStatement();

prestat1 = conn.prepareStatement("insert into addressBook values(?,?,?,?,?)");

prestat2 = conn.prepareStatement("delete from addressBook where id = ?");

prestat3 = conn.prepareStatement("update addressBook set name=?,phone=?,address=?,company=?" +

" where id = ?");

/*pin = conn.prepareStatement("insert into customer values(?,?,?)");

pdel = conn.prepareStatement("delete from customer where num= ?");

pup = conn.prepareStatement("update customer set name=?,address=? where num=?");*/


} catch (Exception e) {

}

}

public void add(){

String id = fid.getText();

String name = fname.getText();

String phone = fphone.getText();

String address = faddress.getText();

String company = fcompany.getText();

try {

prestat1.setString(1, id);

prestat1.setString(2, name);

prestat1.setString(3, phone);

prestat1.setString(4, address);

prestat1.setString(5, company);

prestat1.executeUpdate();

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}


}


public void delete(){

String id = fid.getText();

try {

prestat2.setString(1, id);

prestat2.executeUpdate();

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}


public void update(){

String id = fid.getText();

String name = fname.getText();

String phone = fphone.getText();

String address = faddress.getText();

String company = fcompany.getText();

try {

prestat3.setString(1, name);

prestat3.setString(2, phone);

prestat3.setString(3, address);

prestat3.setString(4, company);

prestat3.setString(5, id);

prestat3.executeUpdate();

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

public void search(){

String keyword = search.getText();

int i = combo.getSelectedIndex();

String index;

if(i==0)

index = "name";

else if(i==1)

index = "address";

else

index = "company";

String q = "select * from addressBook where "+index+"='"+keyword+"' order by id";

select(q);

search.setText("");

}

public void clear(){

fid.setText("");

fname.setText("");

fphone.setText("");

faddress.setText("");

fcompany.setText("");

fid.setEditable(true);

}


public void select(String query){

try{

if(query == null)

query = "select * from addressBook order by id";

rs = stat.executeQuery(query);

// rs안에 데이터가 여부 체크 후 작업

outer.clear();

while (rs.next()) {

msg = new Vector<String>();


msg.add(rs.getString(1));

msg.add(rs.getString(2));

msg.add(rs.getString(3));

msg.add(rs.getString(4));

msg.add(rs.getString(5));

outer.add(msg);

}



}catch(Exception e){}

}


public void actionPerformed(ActionEvent w){

Object o = w.getSource();


try{

if(o==add){ //추가

if(fid.getText().length() > 0)

add();

select(null);


}else if(o==delete){ //삭제

if(fid.getText().length() > 0)

delete();

select(null);


}else if(o==clear){ //지우기

clear();


}else if(o==all){ //전체보기

select(null);


}else if(o==update){ //수정

if(fid.getText().length() > 0)

update();

select(null);


}else if(o==search || o == sbutton){ //검색:버튼을 누르거나 엔터를 치거나

search();


}

//model로 값 설정

if (outer.isEmpty()) {

outer.clear();

msg.clear();


msg.add("찾은 데이터가 없습니다...");

outer.add(msg);

model.setDataVector(outer, noresult);

}else{

model.setDataVector(outer, title);

}

//초기화

clear();

}catch(Exception ew){

ew.printStackTrace();

}

}


public static void main(String[] args) {

AddressBook f = new AddressBook();

f.pack();

f.setVisible(true);

}

}





Comments