본문 바로가기

Learning/SQL

JDBC INSERT

<JDBC INSERT>

 

  • SCOTT 계정에서 NAMECARD라는 명함 테이플을 만들기

 

DROP TABLE NAMECARD;

 

CREATE TABLE NAMECARD(

    NO      NUMBER CONSTRAINT PK_NAMECARD PRIMARY KEY,

    NAME    VARCHAR2(20) NOT NULL,

    MOBILE  VARCHAR2(20) NOT NULL,

    EMAIL   VARCHAR2(40),

    COMPANY VARCHAR2(60)

);

 

 


 

  • 시퀀스 만들기

 

DROP SEQUENCE CARD_NO;

 

CREATE SEQUENCE CARD_NO

INCREMENT BY 1

START WITH 1;

 

 

 


 

  • NAMECARD 테이블에 값 입력

 

INSERT INTO NAMECARD VALUES (

    CARD_NO.NEXTVAL,

    'LALA',

    '010-1234-5678',

    'LALA@naver.com',

    'Naver Com'

);

 

SELECT * FROM NAMECARD;

 

 

 

 


 

  • 자바 실행 파일로 INSERT 입력

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package com.oracle.namecardTest;
 
import java.sql.*//자바 sql 라이브러리 
 
public class Insert {
 
    public static void main(String[] args) {
        //(oracle) jdbc:oracle:thin:@localhost:1521:xe
        //(mySQL) jdbc:mysql://localhost:3306/db이름
//        미리 입력할 오라클 주소, 계정, 비밀번호를 변수로 저장
        String DB_URL = "jdbc:oracle:thin:@127.0.0.1:1521:XE";
        String DB_USER = "scott";
        String DB_PASSWORD = "1234";
//      conn은 오라클 연결을 위한 객체
        Connection conn = null;
//      stmt는 sql문을 실행하기 위한 객체
        Statement stmt = null;
//      rs는 sql문 실행 후 결과값을 받아오는 객체
        //ResultSet rs = null;
 
        String query = "INSERT INTO NAMECARD VALUES (" + 
                "    CARD_NO.NEXTVAL," + 
                "    'LALA'," + 
                "    '010-1234-5678'," + 
                "    'LALA@naver.com'," + 
                "    'Naver Com'" + 
                ")" ;
        
        try {
            //1. 오라클 드라이버 로딩   ( ojdbc6_g.jar )            
            Class.forName("oracle.jdbc.driver.OracleDriver");
        } catch (ClassNotFoundException e ) { //클래스를 못찾았을때 (드라이버 없을때 )
            e.printStackTrace();
        }
 
        try { //DB 연결 부분은 try-catch 문으로 예외 발생시 처리
            //2. DB 연결
            conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
            //3. SQL 문 준비
            stmt = conn.createStatement();
            //4. SQL 쿼리 실행
            stmt.executeUpdate(query);
            
            System.out.println("입력완료!");
            
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                stmt.close();        //State문 닫기
                conn.close();
            } catch (SQLException e) {}
        }
    }
 
}
 
cs

 

 


  • SQL developer에서 INSERT문이 실행되었는지 확인

 

1
SELECT * FROM NAMECARD;
cs

 

 

'Learning > SQL' 카테고리의 다른 글

PreparedStatement  (0) 2020.06.23
JDBC SELECT  (0) 2020.06.23
JDBC Test  (0) 2020.06.23
DCL: 데이터 제어어  (0) 2020.06.23
시퀀스  (0) 2020.06.23