씨네
공부하는 개발자 강씨네
씨네
  • 분류 전체보기 (460)
    • Web (21)
      • HTML (11)
      • CSS (10)
    • JS 관련 (49)
      • JavaScript (27)
      • JQuery (22)
    • TS 관련 (15)
      • TypeScript (15)
    • NodeJS (7)
      • NodeJS (7)
    • 따라하며 배우는 시리즈 (23)
      • NodeJS & ReactJS Basic (23)
      • NodeJS & ReactJS Movie (0)
      • NodeJS & ReactJS Youtube (0)
      • NodeJS & ReactJS ChatBot (0)
    • SPA (14)
      • React (14)
      • Vue (0)
      • Anguler (0)
    • Java 관련 (118)
      • Java (52)
      • JDBC (6)
      • JSP & Servlet (18)
      • Spring Legecy (38)
      • SpringBoot (4)
    • Python (26)
      • Python (20)
      • PyMongo (1)
      • Django (5)
    • Git (24)
      • Github (24)
    • RDB (22)
      • Oracle (21)
      • MySQL (1)
    • NoSQL (5)
      • MongoDB (5)
    • OS (4)
      • Linux (4)
    • 빅데이터 (2)
      • hadoop (2)
    • IDE (20)
      • eclipse (11)
      • VSCODE (4)
      • VisualStudio (1)
      • IntelliJ (1)
      • PyCharm (1)
      • DBeaver (2)
    • Install (3)
      • Tomcat (1)
      • Docker (1)
      • Anaconda (1)
    • 오류&에러 (28)
      • TS (2)
      • NodeJS (7)
      • SQL (8)
      • Java (1)
      • Spring (4)
      • Git (6)
      • 기타 (0)
    • 알고리즘 (67)
      • 수열 (1)
      • 백준(backjoon) (39)
      • Programmers (27)
    • 자격증 (5)
      • SQLD (5)
    • 기타 (2)
    • IT유튜브로 지식쌓기 (2)

공지사항

인기 글

최근 글

티스토리

250x250
hELLO · Designed By 정상우.
씨네

공부하는 개발자 강씨네

[JDBC] insert(데이터 삽입)
카테고리 없음

[JDBC] insert(데이터 삽입)

2022. 3. 3. 13:19
728x90

1. insert의 Statement 방식

package com.test01;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;

public class MTest04 {

	public static void main(String[] args) {
		insertForStatement();
	}
	
	public static void insertForStatement() {
		Scanner sc = new Scanner(System.in);
		System.out.println("부서번호 입력 : ");
		int deptno = sc.nextInt();
		System.out.println("부서이름 입력 : ");
		String dname = sc.next();
		System.out.println("지역이름 입력 : ");
		String loc = sc.next();
		
		//1. 드라이버연결
		try {
		Class.forName("oracle.jdbc.driver.OracleDriver");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		
		//2. 계정연결
		String url = "jdbc:oracle:thin:@localhost:1521:xe";
		String user = "cine";
		String password = "cine";
		
		
		Connection con = null;
		
		try {
		 con = DriverManager.getConnection(url, user, password);
		 // con.setAutoCommit(false);
		} catch (SQLException e) {
			e.printStackTrace();
		}

		
		String sql = " INSERT INTO DEPT "
				+ " VALUES( " + deptno + ", '" + dname + "' , '" + loc + "') ";
		
		Statement stmt = null;
		try {
			//3. Query 준비
			stmt = con.createStatement();
			
			//4. Query 실행 및 리턴
			int res = stmt.executeUpdate(sql);
			if(res > 0) {
				System.out.println("입력 성공");
			}else {
				System.out.println("입력 실패");
			}
			
		}catch (Exception e) {
			e.printStackTrace();
		}finally {
		//5. DB종료
			try {
				stmt.close();
				con.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
}

INSERT 명령을 위한 코드입니다.

이 코드에서 보면 ResultSet이 사용되지 않았습니다.

데이터 삽입명령이기 때문에 데이터를 출력할 필요가 없기 때문입니다.

또한 앞에서는 throws를 했었기에 메인메소드에서 해당 메소드를 호출 할 때 try/catch를 해야하는 번거로움이 있었지만 메소드를 만들때 try/catch를 하면 호출할때 다시 try/catch를 하지 않아도 됩니다.

전체 적인 순서는 select명령을 사용할때와 동일합니다.

​

//1. 드라이버연결
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException e) {
	e.printStackTrace();
}

먼저 드라이버 연결을 해줍니다!

​

//2. 계정연결
String url = "jdbc:oracle:thin:@localhost:1521:xe";
String user = "kh";
String password = "kh";
		
Connection con = null;
		
try {
con = DriverManager.getConnection(url, user, password);
// con.setAutoCommit(false);
} catch (SQLException e) {
	e.printStackTrace();
}

2번째 단계로 계정연결이 필요합니다.

try/catch를 하기위해 Connection con = null;로 주고 아래에

con = DriverManager.getConnection(); 을 해주었습니다.

지금은 주석처리 해놓았지만 con.setAutoCommit(false)는 Connection 객체에서 제공하는 메소드입니다.

setAutoCommit은 ture로 기본설정이 되어있습니다.

또한 Connection 객체에서 commit()메소드와 rollback()메소드를 제공하는데 자동 commit 방지를 위해 setAutoCommit을 false로 수동 설정해주는 것입니다.

​

​

String sql = " INSERT INTO DEPT "
	     	+ " VALUES( " + deptno + ", '" + dname + "' , '" + loc + "') ";
		
Statement stmt = null;
try {
	//3. Query 준비
	stmt = con.createStatement();
			
	//4. Query 실행 및 리턴
	int res = stmt.executeUpdate(sql);
	if(res > 0) {
		System.out.println("입력 성공");
	}else {
		System.out.println("입력 실패");
	}

3번 단계인 쿼리 준비와 4번 단계인 쿼리 실행 및 리턴을 같이 보겠습니다.

해당 코드에서는 res라는 변수가 select에서와는 다르게 추가 되었습니다.

res는 sql문이 수행되었는지 실패하였는지 확인하기 위한 변수라고 볼 수 있는데요.

stmt.executeUpdate(sql)의 명령이 1번 수행되면 값이 1로 변경됩니다.

이 값을 res에 대입하여 res가 0보다 크면 입력 성공, 이외의 결과이면 입력 실패라는 글자를 출력하게 만든것입니다.

또한 select일때 executeQuery와 다르게 executeUpdate를 사용하였습니다.

​


2. insert의 PreparedStatement방식

package com.test01;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;

public class MTest04 {

	public static void main(String[] args) {
		insertForPrepared();
	}
	
	
	public static void insertForPrepared() {
		Scanner sc = new Scanner(System.in);
		System.out.println("부서번호 입력 : ");
		int deptno = sc.nextInt();
		System.out.println("부서이름 입력 : ");
		String dname = sc.next();
		System.out.println("지역이름 입력 : ");
		String loc = sc.next();
		
		//1.
		try {
			Class.forName("oracle.jdbc.driver.OracleDriver");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		
		//2.
		String url = "jdbc:oracle:thin:@localhost:1521:xe";
		String user = "cine";
		String password = "cine";
		Connection con = null;
		
		try {
			con = DriverManager.getConnection(url, user, password);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		//3.
		String sql = " INSERT INTO DEPT "
				   + " VALUES (?, ?, ?) ";
		
		PreparedStatement pstm = null;
		
		try {
			//3. Query준비
			pstm = con.prepareStatement(sql);
			pstm.setInt(1,  deptno);
			pstm.setString(2,  dname);
			pstm.setString(3,  loc);
			//4. Query 실행 및 리턴
			int res = pstm.executeUpdate();
			if(res > 0) {
				System.out.println("입력 성공");
			} else {
				System.out.println("입력 실패");
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			//5. DB종료
			try {
				pstm.close();
				con.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
}

결과는 Statement와 같습니다! ( 저는 삭제하고 똑같은 값을 다시 넣어보았습니다 )

앞선 select 포스팅에서 말씀 드렸던것 처럼 1번 단계인 드라이버연결, 2번 단계인 계정연결, 5번 단계인 DB종료는 Statement 방식과 PreparedStatement 방식이 동일합니다.

​

//3.
		String sql = " INSERT INTO DEPT "
				   + " VALUES (?, ?, ?) ";
		
		PreparedStatement pstm = null;
		
		try {
			//3. Query준비
			pstm = con.prepareStatement(sql);
			pstm.setInt(1,  deptno);
			pstm.setString(2,  dname);
			pstm.setString(3,  loc);
			//4. Query 실행 및 리턴
			int res = pstm.executeUpdate();
			if(res > 0) {
				System.out.println("입력 성공");
			} else {
				System.out.println("입력 실패");
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {

3번 4번 단계인 Query 준비부터 실행 및 리턴까지의 코드를 보겠습니다.

우선 Statement 객체가 아닌 PreparedStatement객체를 사용할 경우

String sql = " INSERT INTO DEPT VALUES (?, ?, ?) ";

SQL명령에 ?가 들어갑니다.

//3. Query준비
pstm = con.prepareStatement(sql);
pstm.setInt(1,  deptno);
pstm.setString(2,  dname);
pstm.setString(3,  loc);

해당 ?에 들어갈 값들을 미리 준비합니다.

int res = pstm.executeUpdate();

SQL명령이 잘 수행 되었다면 res에는 1이라는 값이 대입이 되어있어야 합니다.

728x90
    씨네
    씨네
    개발자 씨네가 공부하는 내용을 기록 겸 공유하는 블로그입니다!

    티스토리툴바