Notice
Recent Posts
Recent Comments
관리 메뉴

Developer Gonie

[7주차] 6. delete 문 실행하기 본문

K-DigitalTraining 강의/3. JDBC(Java + Oracle DB)

[7주차] 6. delete 문 실행하기

이대곤 2022. 6. 21. 09:13

1. 가장 원시적으로 delete 문을 실행하는 방법

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

public class Delete {
	public static void main(String[] args) {
		String driver = "oracle.jdbc.driver.OracleDriver";
		String url = "jdbc:oracle:thin:@localhost:1521:orcl";
		String id = "jspid";
		String pw = "jsppw";
		Connection conn = null;

		try {
			// 1. 드라이버 로드
			Class.forName(driver);

			// 2. 계정에 접속
			conn = DriverManager.getConnection(url, id, pw);

			// 3. 명령어 분석
			String sql = "delete from dbtest where num = 3";
			PreparedStatement ps = conn.prepareStatement(sql);			

			// 4. 분석된 명령어를 실행하고 그 결과를 가져옴
			int cnt = ps.executeUpdate(); // 보통 여기서 에러나면 sql 쿼리문에 오타가 있거나 한 경우가 많음
			System.out.println("cnt :" + cnt); // 성공적으로 insert 한 개수가 반환됨

			// 5. 접속끊기 -> 접속을 끊으면 자동으로 commit됨
			conn.close();

		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

2. 각 컬럼 값을 변수에 담았다가  update 문을 실행하는 방법1

* 문자열이 컬럼 값으로 들어가야 하는 경우 " ' " 작은 따옴표로 감싸줘야 한다.

// 3. 명령어 분석
int dl_num = 3;
String sql = "delete from dbtest where num = " + dl_num;
PreparedStatement ps = conn.prepareStatement(sql);

3. 각 컬럼 값을 변수에 담았다가  update 문을 실행하는 방법2(가장 이상적)

* ? 는 위치홀더라고 부른다.

* 분석을 진행한 이후에 set메소드로 물음표 자리를 채워넣는 순서에 주의

// 3. 명령어 분석
int dl_num = 3;
String sql = "delete from dbtest where num = ?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, dl_num);
Comments