자바

* Oracle 설치 

- http://oracle.com

- Oracle 12c Standard Edition 다운로드

* Oracle 설치시 주의사항

   1) 컴퓨터 이름이 한글이면 안됨

   2) 사용자 계정이 한글이면 안됨

   3) 디렉토리 이름이 한글이면 안됨

      - 설치 디렉토리 사이의 경로에도 한글이 있으면 안됨

   4) 디렉토리 이름에 공백이 있으면 안됨

      - 설치 디렉토리 사이의 경로에도 공백이 있으면 안됨

   5) 설치시 에러 해결

      - oracle 다시 설치

       * 서비스 – 리스너 ~ 중지 

       * (실행)- regedit - 레지스트리 편집기에서 'oracle'관련 내용 제거

       * 디렉토리 - oracle 디렉토리 삭제

       * oracle 다시 설치

* 기본 사용자 계정

1) sys : 오라클의 최상위 관리자 계정. 데이터베이스에서 발생하는 모든 문제를 처리할 수 있는 권한을 가짐

2) system:  관리자 계정 중의 하나 

* 주요 용어

- 테이블: 관계형DB에서 기본 데이터 저장구조. 

- Record(Row) : 하나의 유효한 데이터. COLUMN들의 집합

- COLUMN : 테이블의 열

- PRIMARY KEY : 기본키. 테이블에서 각 Record를 유일하게 구분하는 COLUMN

- FOREIGN KEY : 외래키. 다른 테이블의 기본키를 참조하는 COLUMN

- NULL : 데이터가 존재하지 않는 FIELD

* 실습용 계정 및 실습용 데이터 생성

- hr 계정이 있는 경우(Oracle 11g Express Edition)

관리자 계정으로 로그인

alter user hr identified by hr account unlock;

 

hr 계정이 활성화됨

 

- hr 계정이 없는 경우(Oracle 12c Standard Edition)

http://edu.lifesoft.org/data/sql/hr_data.sql 다운로드

sqlplus 에서 실행

@ d:\hr_data.sql

hr 계정이 생성되고 실습용 샘플 데이터가 입력됨

 

* Oracle Tool

- Toad : 유료이며 가장 많이 사용되는 툴

- SQL Developer : 무료이며 오라클사에서 배포하는 툴

* Toad Freeware 64bit 설치

- http://toadworld.com

* jdbc library 복사 : 

http://www.oracle.com/technetwork/database/features/jdbc/jdbc-drivers-12c-download-1958347.html   에서 오라클 버전에 맞는 jar 파일을 WebContent/WEB-INF/lib 디렉토리에 복사

 

 

sqlplus / as sysdba

-- 테이블 스페이스 생성

create tablespace 
java (테이블 스페이스 이름)
datafile 'D:\oracleDB\XE\java.dbf'  (데이터파일경로)
size 50m (초기사이즈)
autoextend on (자동증가)
next 10m (자동 증가 사이즈)
maxsize unlimited; (최대 사이즈)

 


create tablespace java datafile 'D:\oracleDB\XE\java.dbf'  size 50m autoextend on next 10m maxsize unlimited;

 

11g => 12c

-- 11g 와 호환

alter session set "_ORACLE_SCRIPT"=true;

-- 사용자 계정 만들기

create user 아이디 identified by 비번

default tablespace 테이블스페이스 이름

create user java identified by 1111 default tablespace java;


-- 유저 목록 보기

SELECT USERNAME FROM DBA_USERS

 

--  사용자에게 권한 부여

-- grant 권한 to 아이디;

-- connect : 로그인 권한

-- resource : 자원을 사용할 수 있는 권한

-- dba : db 관리자 권한

grant create view, connect, resource, dba  to java;

-- 점수 테이블
-- 토드 실행 F9
-- 실행
-- varchar , varchar2 : 최대 4000 byte
-- number  실수 값 지원
-- number() 괄호 안에 숫자를 넣으면 제한된 값
-- numer(3) 정수 3자리

create table score (

 student_no varchar2(20) primary key,
 name varchar2(20) not null,
 kor number(3) not null,    
 eng number(3) not null,
 mat number(3) not null

);

 

insert into score values('1' , 'kim' , 90, 80, 70);

select * from score;


commit;

 

 

 

class 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 Connection oracleConn(){
		Connection conn=null;
		try{
			//db 접속 정보가 저장되 db.prop 파일을 로딩
			FileInputStream fis =new FileInputStream("oracle.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 java20_oracle;

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() {
		
	}

	public ScoreDTO(String student_no, String name, int kor, int eng, int mat) {
		super();
		this.student_no = student_no;
		this.name = name;
		this.kor = kor;
		this.eng = eng;
		this.mat = mat;
	}

	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 + "]";
	}
		
	
	
}

 

class ScoreDAO

package java20_oracle;

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<Object> listScore(){
		Vector<Object> items=new Vector<Object>();
		Connection conn=null;
		PreparedStatement pstmt=null;
		ResultSet rs=null;
		try{
			conn=DBConnectManager.oracleConn();
			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);
			rs=pstmt.executeQuery();
			while(rs.next()){
				//JTable 이 Vecotr 만 들어간다.
				Vector<Object> row=new Vector<>();
				row.add(rs.getString("student_no"));
				row.add(rs.getString("name"));
				row.add(rs.getInt("kor"));
				row.add(rs.getInt("eng"));
				row.add(rs.getInt("mat"));
				row.add(rs.getInt("tot"));
				row.add(rs.getDouble("avg"));
				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("평균");
		table = new JTable();
		//테이블 모델 생성
		//dao 에서 받아온 데이터로 테이블 모델 생성
		DefaultTableModel model=new DefaultTableModel(dao.listScore(), col);
		//테이블에 데이터 모델을 입력함
		table.setModel(model);

 

 

class ScoreList

package java20_oracle;

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;

public class ScoreList extends JFrame {

	private static final long serialVersionUID = 1L;
	
	private JPanel contentPane;
	private JTable table;

	private ScoreDAO dao;
	private Vector<Object> data, col; // 테이블의 데이터와 제목 컬럼을 위한  벡터
	
	
	
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					ScoreList frame = new ScoreList();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public ScoreList() {
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 644, 496);
		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("평균");
		table = new JTable();
		//테이블 모델 생성
		//dao 에서 받아온 데이터로 테이블 모델 생성
		DefaultTableModel model=new DefaultTableModel(dao.listScore(), col);
		//테이블에 데이터 모델을 입력함
		table.setModel(model);
		
		//스크롤페인에 테이블을 붙임
		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setBounds(12, 69, 604, 379);
		contentPane.add(scrollPane);
		scrollPane.setViewportView(table);
		
	}
	
	

}

 

 

 

 

 

 

about author

PHRASE

Level 60  머나먼나라

천생 버릇은 임을 봐도 못 고친다 , 타고난 버릇은 고치기 어렵다는 말.

댓글 ( 4)

댓글 남기기

작성