자바

--데이터 베이스 선택
use java ;

-- 점수 테이블
create table score (
    
    student_no varchar(50) primary key,
    name varchar(50) not null,
    kor int default 0,
    eng int default 0,
    mat int default 0,
    tot int default 0,
    avg double default 0

);

-- 레코드 입력

insert into score values ('1', '김철수', 90, 80, 70, 240, 80);

-- 확인

select * from score;


 

JFrame  테이블형식으로  목록 저장 Vector

	//학생 점수를 벡테어 저장하여 리턴
	public Vector listScore(){
		Vector items =new Vector(); //모든 자료형을 담을 수 있음. 순서대로 저장
		Connection conn =null; //DB 접속 처리
		PreparedStatement pstmt=null; // sql 명령어 실행
		ResultSet rs =null; // select 명령어의 결과셋(레코드세)을 1레코드씩 읽기
		try {
			conn=DBConnectManager.dbConn();
			String sql ="select student_no, name, kor,  eng , mat , ( kor+ eng+ mat) as tot , (( kor+eng+mat)/3.0) as avg from score";
			pstmt=conn.prepareStatement(sql);//sql 명령어 실행 객체 생성
			rs=pstmt.executeQuery();//실행결과를 rs에 전달
			while(rs.next()){ //다음 레코드가 있으면 true, 없으면 false
				//결과셋.get자료형("컬럼이름")
				Vector row=new Vector();
				
				String student_no=rs.getString("student_no");
				String name=rs.getString("name");
				int kor=rs.getInt("kor");
				int eng=rs.getInt("eng");
				int mat=rs.getInt("mat");
				int tot=rs.getInt("tot");
				double avg=rs.getDouble("avg");
				row.add(student_no);
				row.add(name);
				row.add(kor);
				row.add(mat);
				row.add(eng);
				row.add(tot);
				row.add(kor);
				items.add(row);//벡터에 벡터를 저장
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			DBConnectManager.close(conn, pstmt, rs);
		}
		return items;
	}
	

 

	//dao 객체 생성
		dao=ScoreDAO.getInstance();
		//테이블의 제목 컬럼 지정
		col=new Vector();
		col.add("학번");
		col.add("이름");
		col.add("국어");
		col.add("영어");
		col.add("수학");
		col.add("총점");
		col.add("평균");
		
		
		//점수 리스트를 불러옴
		//테이블 모델 : JTable에 입력될 데이터
		//JTable 에 입력 가능한 데이터 :배열(수정, 삭제가 안됨), Object, Vector
		// new DefaultTableModel(데이터, 제목열)
		DefaultTableModel model=new DefaultTableModel(dao.listScore(), col){
			
			//테이블 내용을 편집하지 못하도록 막음
			@Override
			public boolean isCellEditable(int row, int column) {
				return false;
			}
		};
		
				
		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setBounds(35, 137, 551, 294);
		contentPane.add(scrollPane);
		
		
		table = new JTable(model);

 

 

화면전환 현재창 닫고 새창 열기

static ScoreList frame;	


		JButton btnNewButton = new JButton("New button");
		btnNewButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				MyNewWindowClass newWindow = new MyNewWindowClass();
				newWindow.setVisible(true);
				frame.setVisible(false);
				
			}
		});

 

현재 창만 종료

setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

 

 

테이블 클릭시 데이터 값 가져오기 및  이벤트 걸기

		table = new JTable(model);
		scrollPane.setViewportView(table);
		//JTable에 마우스 이벤트 추가
		table.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				//마우스 클릭한 행의 인덱스 값
				int idx=table.getSelectedRow();
				//테이블.getValueAt(행의 인덱스 , 컬럼의 인덱스)
				tfStudentNo.setText(table.getValueAt(idx, 0)+"");
				tfName.setText(table.getValueAt(idx, 1)+"");
				tfKor.setText(table.getValueAt(idx, 2)+"");
				tfEng.setText(table.getValueAt(idx, 3)+"");
				tfMat.setText(table.getValueAt(idx, 4)+"");
			}
		});

 

 전체 코드 

 

 

DBConnectManager

package common.db;

import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Properties;

public class DBConnectManager {

	public static Connection dbConn(){
		Connection conn=null;
		try{
			//db 접속 정보가 저장되 db.prop 파일을 로딩
			FileInputStream fis =new FileInputStream("db.prop");
			Properties prop=new Properties();
			prop.load(fis);
			String url=prop.getProperty("url");
			String id=prop.getProperty("id");
			String password=prop.getProperty("password");

			//mysql에 접속 처리
			conn=DriverManager.getConnection(url, id, password);
		}catch(Exception e){
			e.printStackTrace();
		}
		return conn;
	}
	
	
	public static void close(Connection conn){
		try {
			if(conn!=null)conn.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static void close(PreparedStatement pstmt){
		try {
			if(pstmt!=null)pstmt.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static void close(ResultSet rs){
		try {
			if(rs!=null)rs.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static void close(Connection conn, PreparedStatement pstmt ){
				
		try{
			if(pstmt!=null)pstmt.close();
		}catch(Exception e){
			e.printStackTrace();
		}
		
		try {
			if(conn!=null)conn.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	
	}
	

	public static void close(Connection conn, PreparedStatement pstmt, ResultSet rs){

		try{
			if(rs!=null)rs.close();
		}catch(Exception e){
			e.printStackTrace();
		}
				
		try{
			if(pstmt!=null)pstmt.close();
		}catch(Exception e){
			e.printStackTrace();
		}
		
		try {
			if(conn!=null)conn.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	
	}
	
	
	
	public static void close(Connection conn, Statement stmt, ResultSet rs){

		try{
			if(rs!=null)rs.close();
		}catch(Exception e){
			e.printStackTrace();
		}
				
		try{
			if(stmt!=null)stmt.close();
		}catch(Exception e){
			e.printStackTrace();
		}
		
		try {
			if(conn!=null)conn.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	
	}
	
	
	
	
	
}

 

class ScoreDTO

package java19.score;


//MVC pattern :
// Model(모델, 데이터 저장 /처리 로직)
// View(뷰, 화면 처리 클래스)
//Controller(컨트롤러, 프로그램의 흐름 제어)

public class ScoreDTO {
	private String student_no;
	private String name;
	private int kor;
	private int eng;
	private int mat;
	private int tot;
	private double avg;
	
	public ScoreDTO() {
		super();
	}
	public ScoreDTO(String student_no, String name, int kor, int eng, int mat) {
		this.student_no = student_no;
		this.name = name;
		this.kor = kor;
		this.eng = eng;
		this.mat = mat;
		tot=kor+eng+mat;
		avg=tot/3.0;
	}
	public String getStudent_no() {
		return student_no;
	}
	public void setStudent_no(String student_no) {
		this.student_no = student_no;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getKor() {
		return kor;
	}
	public void setKor(int kor) {
		this.kor = kor;
	}
	public int getEng() {
		return eng;
	}
	public void setEng(int eng) {
		this.eng = eng;
	}
	public int getMat() {
		return mat;
	}
	public void setMat(int mat) {
		this.mat = mat;
	}
	public int getTot() {
		return tot;
	}
	public void setTot(int tot) {
		this.tot = tot;
	}
	public double getAvg() {
		return avg;
	}
	public void setAvg(double avg) {
		this.avg = avg;
	}
	
	
	@Override
	public String toString() {
		return "ScoreDTO [student_no=" + student_no + ", name=" + name + ", kor=" + kor + ", eng=" + eng + ", mat="
				+ mat + ", tot=" + tot + ", avg=" + avg + "]";
	}
	
	
	
	
	
	
	
}

 

package java19.score;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Vector;

import common.db.DBConnectManager;

public class ScoreDAO {
 
	private static ScoreDAO dao;
	private ScoreDAO(){
		
	}
	public static ScoreDAO getInstance(){
		if(dao==null){
			dao =new ScoreDAO();
		}
		return dao;
	}
	
	//학생 점수를 벡테어 저장하여 리턴
	public Vector listScore(){
		Vector items =new Vector(); //모든 자료형을 담을 수 있음. 순서대로 저장
		Connection conn =null; //DB 접속 처리
		PreparedStatement pstmt=null; // sql 명령어 실행
		ResultSet rs =null; // select 명령어의 결과셋(레코드세)을 1레코드씩 읽기
		try {
			conn=DBConnectManager.dbConn();
			String sql ="select student_no, name, kor,  eng , mat , ( kor+ eng+ mat) as tot , (( kor+eng+mat)/3.0) as avg from score";
			pstmt=conn.prepareStatement(sql);//sql 명령어 실행 객체 생성
			rs=pstmt.executeQuery();//실행결과를 rs에 전달
			while(rs.next()){ //다음 레코드가 있으면 true, 없으면 false
				//결과셋.get자료형("컬럼이름")
				Vector row=new Vector();
				
				String student_no=rs.getString("student_no");
				String name=rs.getString("name");
				int kor=rs.getInt("kor");
				int eng=rs.getInt("eng");
				int mat=rs.getInt("mat");
				int tot=rs.getInt("tot");
				double avg=rs.getDouble("avg");
				row.add(student_no);
				row.add(name);
				row.add(kor);
				row.add(mat);
				row.add(eng);
				row.add(tot);
				row.add(kor);
				items.add(row);//벡터에 벡터를 저장
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			DBConnectManager.close(conn, pstmt, rs);
		}
		return items;
	}
	
	
	//학생 점수를 테이블에 저장
	public int insertScore(ScoreDTO dto){
		int result=0; 
		Connection conn=null;
		PreparedStatement pstmt=null;
		try{
			conn=DBConnectManager.dbConn();
			String sql="insert into score( student_no, name, kor, eng, mat, tot, avg)"
					+ " values (?, ?, ?, ?, ?, ?, ? )";
			pstmt=conn.prepareStatement(sql);
			pstmt.setString(1, dto.getStudent_no());
			pstmt.setString(2, dto.getName());
			pstmt.setInt(3, dto.getKor());
			pstmt.setInt(4, dto.getEng());
			pstmt.setInt(5, dto.getMat());
			pstmt.setInt(6, dto.getTot());
			pstmt.setDouble(7, dto.getAvg());
			result=pstmt.executeUpdate();
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			DBConnectManager.close(conn, pstmt);
		}
		return result;
	}
	
	
	
	
}


 

 

class ScoreList

package java19.score;

import java.awt.EventQueue;
import java.util.Vector;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.ActionEvent;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

public class ScoreList extends JFrame {

	private JPanel contentPane;
	private JTable table;
	static ScoreList frame;
	
	
	private ScoreDAO dao;
	private Vector data, col; //data(점수리스트), col(테이블이 헤더)
	
	private JTextField tfStudentNo;
	private JTextField tfName;
	private JTextField tfKor;
	private JTextField tfMat;
	private JTextField tfEng;
	
	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					 frame = new ScoreList();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public ScoreList() {
		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		setBounds(100, 100, 651, 479);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);
		
		//dao 객체 생성
		dao=ScoreDAO.getInstance();
		//테이블의 제목 컬럼 지정
		col=new Vector();
		col.add("학번");
		col.add("이름");
		col.add("국어");
		col.add("영어");
		col.add("수학");
		col.add("총점");
		col.add("평균");
		
		
		//점수 리스트를 불러옴
		//테이블 모델 : JTable에 입력될 데이터
		//JTable 에 입력 가능한 데이터 :배열(수정, 삭제가 안됨), Object, Vector
		// new DefaultTableModel(데이터, 제목열)
		DefaultTableModel model=new DefaultTableModel(dao.listScore(), col){
			
			//테이블 내용을 편집하지 못하도록 막음
			@Override
			public boolean isCellEditable(int row, int column) {
				return false;
			}
		};
		
				
		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setBounds(35, 137, 551, 294);
		contentPane.add(scrollPane);
		
		
		table = new JTable(model);
		scrollPane.setViewportView(table);
		//JTable에 마우스 이벤트 추가
		table.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				//마우스 클릭한 행의 인덱스 값
				int idx=table.getSelectedRow();
				//테이블.getValueAt(행의 인덱스 , 컬럼의 인덱스)
				tfStudentNo.setText(table.getValueAt(idx, 0)+"");
				tfName.setText(table.getValueAt(idx, 1)+"");
				tfKor.setText(table.getValueAt(idx, 2)+"");
				tfEng.setText(table.getValueAt(idx, 3)+"");
				tfMat.setText(table.getValueAt(idx, 4)+"");
			}
		});
		
		
		JButton btnNewButton = new JButton("New button");
		btnNewButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				MyNewWindowClass newWindow = new MyNewWindowClass();
				newWindow.setVisible(true);
				//frame.setVisible(false);
				
			}
		});
		btnNewButton.setBounds(513, 10, 97, 23);
		contentPane.add(btnNewButton);
		
		JLabel lblNewLabel = new JLabel("학번");
		lblNewLabel.setBounds(28, 14, 57, 15);
		contentPane.add(lblNewLabel);
		
		JLabel lblNewLabel_1 = new JLabel("이름");
		lblNewLabel_1.setBounds(233, 13, 57, 15);
		contentPane.add(lblNewLabel_1);
		
		JLabel lblNewLabel_2 = new JLabel("국어");
		lblNewLabel_2.setBounds(28, 45, 57, 15);
		contentPane.add(lblNewLabel_2);
		
		JLabel lblNewLabel_3 = new JLabel("영어");
		lblNewLabel_3.setBounds(28, 76, 57, 15);
		contentPane.add(lblNewLabel_3);
		
		JLabel lblNewLabel_4 = new JLabel("수학");
		lblNewLabel_4.setBounds(233, 48, 57, 15);
		contentPane.add(lblNewLabel_4);
		
		tfStudentNo = new JTextField();
		tfStudentNo.setBounds(71, 11, 116, 21);
		contentPane.add(tfStudentNo);
		tfStudentNo.setColumns(10);
		
		tfName = new JTextField();
		tfName.setBounds(276, 10, 116, 21);
		contentPane.add(tfName);
		tfName.setColumns(10);
		
		tfKor = new JTextField();
		tfKor.setBounds(71, 42, 116, 21);
		contentPane.add(tfKor);
		tfKor.setColumns(10);
		
		tfEng = new JTextField();
		tfEng.setBounds(71, 73, 116, 21);
		contentPane.add(tfEng);
		tfEng.setColumns(10);
		
		tfMat = new JTextField();
		tfMat.setBounds(276, 45, 116, 21);
		contentPane.add(tfMat);
		tfMat.setColumns(10);
		
		JButton btnNewButton_1 = new JButton("점수저장");
		btnNewButton_1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				//사용자가 입력한 값
				String student_no=tfStudentNo.getText();
				String name=tfName.getText();
				int kor=Integer.valueOf(tfKor.getText());
				int eng=Integer.valueOf(tfEng.getText());
				int mat=Integer.valueOf(tfMat.getText());
				int result=dao.insertScore(new ScoreDTO(student_no, name, kor, eng, mat));
				if(result==1){//insert 성공하면 1이 리턴
					JOptionPane.showMessageDialog(ScoreList.this, "저장되었습니다");
					//테이블 모델을 갱신
					DefaultTableModel model=new DefaultTableModel(dao.listScore(), col){
						
						//테이블 내용을 편집하지 못하도록 막음
						@Override
						public boolean isCellEditable(int row, int column) {
							return false;
						}
					};
					//테이블에 모델을 적용
					table.setModel(model);
					//입력란 초기화
					tfStudentNo.setText("");
					tfName.setText("");
					tfKor.setText("");
					tfEng.setText("");
					tfMat.setText("");
					tfStudentNo.setFocusable(true);
					tfStudentNo.requestFocus();//입력포커스를 이동시킴
				}else{
					JOptionPane.showMessageDialog(ScoreList.this, "저장에 실패 하였습니다.");
				}
			}
		});
		btnNewButton_1.setBounds(276, 86, 97, 23);
		contentPane.add(btnNewButton_1);
	}
	
	
	
}

 

 

 

 

 

 

 

 

about author

PHRASE

Level 60  머나먼나라

가르침을 받는 자는 스스로 와서 배워야 한다. 이쪽에서 가서 가르친다는 것은 아직 들은 적이 없다. 배우고 싶은 생각이 있어야 공부가 되는 것이지 가르치는 자가 억지로 가르쳐도 아무 성과가 없다는 뜻. -예기

댓글 ( 4)

댓글 남기기

작성