본문 바로가기
STUDY/JAVA

Java 21일차(1) - 다른 컴퓨터의 데이터베이스와 연결

by Anne of Green Galbes 2019. 2. 6.

1. setAutoCommit

○ 모든 데이터가 오류없이 ㅈ대로 들어가도록 하기 위해서 사용한다

○ 하나라도 데이터가 잘못 들어가면 롤백되어 취소


① test1, test2, test3 테이블 생성

○ test1

create table test1

(id number primary key,

name varchar2(10) not null);

○ test2

create table test2

(id number primary key,

birth date not null,

constraint fk_test2_id foreign key(id)

references test1(id));

○ test3

create table test3

(id number primary key,

tel varchar2(20) not null,

constraint fk_test3_id foreign key(id)

references test1(id));

▶ test2와 test3의 id는 test1의 id를 참조키로 사용

② TclMain 작성
○ test1 : 아이디, 이름
sql = String.format("insert into test1 (id,name) values (%d,'%s')", id,name);
○ test2 : 아이디, 생일
sql = String.format("insert into test2 (id,birth) values (%d,'%s')", id,birth);
○ test3 : 아이디, 번호
sql = String.format("insert into test3 (id,tel) values (%d,'%s')", id,tel);

package com.day21;


import java.sql.Connection;

import java.sql.Statement;

import java.util.Scanner;

import com.db.DBConn;


public class TclMain {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

Connection conn = DBConn.getConnection();

Statement stmt = null;

String sql;

int ch;

int id;

String name,birth,tel;

try {

while(true){

do{

System.out.print("1.입력  2.출력 3.종료 : ");

ch = sc.nextInt();

}while(ch<1 || ch>3);

switch (ch) {

case 1:

conn.setAutoCommit(false);


System.out.print("아이디[숫자]:");

id = sc.nextInt();

System.out.print("이름:");

name = sc.next();

System.out.print("생일[yyyy-mm-dd]:");

birth = sc.next();

System.out.print("번호:");

tel = sc.next();

sql = String.format("insert into test1 (id,name) values (%d,'%s')", id,name);

stmt = conn.createStatement();

stmt.executeUpdate(sql);

stmt.close();

sql = String.format("insert into test2 (id,birth) values (%d,'%s')", id,birth);

stmt = conn.createStatement();

stmt.executeUpdate(sql);

stmt.close();

sql = String.format("insert into test3 (id,tel) values (%d,'%s')", id,tel);

stmt = conn.createStatement();

stmt.executeUpdate(sql);

stmt.close();

conn.commit();

break;

case 2:

//출력

break;

case 3:

DBConn.close();

System.exit(0);

}

}

} catch (Exception e) {

System.out.println(e.toString());

}

}

}

결과

1.입력  2.출력  3.종료 : 1

아이디[숫자]:111

이름:SUZI

생일[yyyy-mm-dd]:1994-10-10

번호:010-0000-1111


1.입력  2.출력  3.종료 : 1

아이디[숫자]:222

이름:SUNKIST&ORANGE  ▶ 이름은 최대 10자. 의도적으로 오류 발생

생일[yyyy-mm-dd]:2003-05-05

번호:010-5555-3333

java.sql.SQLException: ORA-12899: "SUZI"."TEST1"."NAME" 열에 대한 값이 너무 큼(실제: 14, 최대값: 10)

▲ 222 SUNKIST&ORANGE 2003-05-05 010-5555-3333은 insert되지 않음



2. 다른 컴퓨터의 데이터베이스와 연결


① 모든 컴퓨터에서 실행

○ 방화벽 해제

방화벽에서 인바운드규칙 1521번 포트 열어준다

ID,PW 일치 시켜야 됨

(연결하고자 하는 테이블의 사용자 ▶ SUZI,A123 : 대소문자구분)

▶ 제어판 > 방화벽 > 고급설정 > 인바운드 > 새 규칙 > 포트 > 1521번 > 오라클포트/1521








② 서버에서 실행

SUZI 계정으로 실행 ▶ SUZI계정의 테이블 사용

○ 사용하는 테이블 작성

○ 기본정보(아이디,비밀번호,이름...) basicdata

create table basicdata

(id varchar2(10) primary key,

pwd varchar2(20) not null,

name varchar2(20) not null);

○ 상세정보(전화,생일...) ▶ detaildata       

create table bang

(tableno number(5),

id varchar2(10),

text varchar2(100),

inputdate date not null,

CONSTRAINT FK_BANG_ID FOREIGN KEY(ID)

REFERENCES BASICDATA(ID)) ;

○ 방명록(번호,이름(조인),아이디,내용,날짜...) bang

create table bang

(tableno number(5),

id varchar2(10),

text varchar2(100),

inputdate date not null);

○ 시퀀스 : tableno

CREATE SEQUENCE tableno

START WITH 1

INCREMENT BY 1

NOMAXVALUE

NOCYCLE

NOCACHE;


③ 클라이언트에서 실행

○ sys 계정으로 실행

데이타베이스 링크를 만드는 과정

GRANT CREATE DATABASE LINK TO SUZI;

○ SUZI 계정으로 실행

CREATE DATABASE LINK link_test                 ▶link_test : 데이타베이스 링크 이름

CONNECT TO SUZI IDENTIFIED BY "A123"    ▶ 서버의 사용자/비밀번호

USING

'(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)

(HOST=XXX.XXX.XXX.XXX)(PORT=1521))    ▶ XXX.XXX.XXX.XXX : 서버 IP

(CONNECT_DATA=(SERVICE_NAME=DB명)))';    ▶ DB명 : EXPRESS버전은 XE

○링크 삭제

drop DATABASE LINK link_test;

○연결테스트

SELECT * FROM basicdata@link_test;                               

insert into basicdata@link_test values ('11','11','suzi');        

SELECT * FROM score@link_test;

테이블@데이타베이스링크


댓글