JAVA_35_ExecuteUpdate_JDBC(오라클)

hyeong taek jo·2023년 7월 15일

JAVA

목록 보기
35/39

📌ExecuteUpdate 예시

  • 수행결과로 Int 타입의 값을 반환
  • SELECT 구문을 제외한 다른 구문을 수행할 때 사용
  • INSERT / DELETE / UPDATE 관련 구문에서는 반영된 레코드의 건수를 반환
  • CREATE / DROP 관련 구문에서는 -1 을 반환
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;

public class OraInsert {

	public static void main(String[] args) throws SQLException {
		Scanner sc = new Scanner(System.in);
		System.out.println("부서번호 입력?"); String deptno = sc.nextLine();
		System.out.println("부서명 입력?"); String dname = sc.nextLine();
		System.out.println("위치 입력?"); String loc = sc.nextLine();
		
		Connection conn = null;
		Statement stmt = null;
		
		String driver = "oracle.jdbc.driver.OracleDriver";
		String url    = "jdbc:oracle:thin:@localhost:1521:xe";
		
		String sql  = String.format("Insert Into dept values(%s,'%s','%s')",deptno,dname,loc);
		                               // deptno는 숫자이지만 문자열로 변수를 받았다 하지만 오류가 안나는건 위에
		                               // '' 이걸 작성안해주면 숫자로 인식한다.
		
		System.out.println("sql->"+sql);
		
		try {
			Class.forName(driver); //driver 변수로 안하고 바로 작성해도 되지만 보기편하라고 변수로 받은 것
			conn = DriverManager.getConnection(url,"scott","tiger");
			stmt = conn.createStatement();
			//result Set
			int result = stmt.executeUpdate(sql); // 수행 --> excuteUpdate int로 받아야함
			if (result > 0 ) System.out.println("입력성공 ");
			else             System.out.println("입력실패");
		} catch(Exception e) {
			System.out.println(e.getMessage());
		} finally {
			if (stmt != null) stmt.close();
			if (stmt != null) conn.close();
		}
		sc.close();
	}
	// 자바는 자동으로 commit된다.
}
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;

public class OraUpdate {

	public static void main(String[] args) throws SQLException {
		Scanner sc = new Scanner(System.in);
		System.out.println("수정할 부서를 입력하세요? "); String deptno = sc.nextLine();
		System.out.println(" 부서명? "); String dname = sc.nextLine();
		System.out.println(" 근무지? "); String loc = sc.nextLine();
		String sql = String.format("UPDATE dept SET dname = '%s' LOC = '%s' WHERE deptno = %s",dname,loc,deptno);
		
		String driver = "oracle.jdbc.driver.OracleDriver";
		String url    = "jdbc:oracle:thin:@localhost:1521:xe";
		Connection conn = null;
		Statement stmt = null;

		System.out.println("sql->" + sql);
		
		try {
			Class.forName(driver); 
			conn = DriverManager.getConnection(url,"scott","tiger");
			stmt = conn.createStatement();
			//result Set
			int result = stmt.executeUpdate(sql);
			if (result > 0 ) System.out.println("입력성공 ");
			else             System.out.println("입력실패");
		} catch(Exception e) {
			System.out.println(e.getMessage());
		} finally {
			if (stmt != null) stmt.close();
			if (stmt != null) conn.close();
		}
		sc.close();
	}
}
profile
마포구 주민

0개의 댓글