Execute
1. 수행결과로 Boolean 타입의 값을 반환합니다.
2. 모든 구문을 수행할 수 있습니다.
execute 함수를 사용하는 방법입니다.
-> 리턴값이 ResultSet 일 경우에는 true, 이 외의 경우에는 false 로 출력됩니다.
-> 리턴값이 ResultSet 이라고 하여 ResultSet 객체에 결과값을 담을 수 없습니다.
PreparedStatement pstmt = con.prepareStatement("INSERT INTO SAMPLE_TABLE VALUES (?, ?)");
pstmt.setInt(1, 200);
pstmt.setString(2, "Jerry");
boolean result = pstmt.execute();
System.out.println("Result : " + result);Result : false
pstmt = con.prepareStatement("SELECT ID, NAME FROM SAMPLE_TABLE");
boolean result2 = pstmt.execute();
System.out.println("Result2 : " + result2);Result2 : true
반환 타입으로 boolean 타입을 사용하지 않는 경우 다음과 같은 메세지가 출력됩니다.
error: incompatible types: boolean cannot be converted to ResultSet
ExecuteQuery
1. 수행결과로 ResultSet 객체의 값을 반환합니다.
2. SELECT 구문을 수행할 때 사용되는 함수입니다.
executeQuery 함수를 사용하는 방법입니다.
-> ResultSet 객체에 결과값을 담을 수 있습니다.
pstmt = con.prepareStatement("SELECT ID, NAME FROM SAMPLE_TABLE");
ResultSet rs = pstmt.executeQuery();
while (rs.next())
{
System.out.println("ID = " + rs.getInt(1) + ", NAME = " + rs.getString(2));
}ID = 100, NAME = Jerry
ExecuteUpdate
1. 수행결과로 Int 타입의 값을 반환합니다.
2. SELECT 구문을 제외한 다른 구문을 수행할 때 사용되는 함수입니다.
executeUpdate 함수를 사용하는 방법입니다.
-> INSERT / DELETE / UPDATE 관련 구문에서는 반영된 레코드의 건수를 반환합니다.
-> CREATE / DROP 관련 구문에서는 -1 을 반환합니다.
pstmt = con.prepareStatement("CREATE TABLE SAMPLE_TABLE ( ID INTEGER, NAME CHAR(20) )");
int ret = pstmt.executeUpdate(); System.out.println("Return : " + ret);
Return : -1
pstmt = con.prepareStatement("UPDATE SAMPLE_TABLE SET NAME=? WHERE ID = ?");
pstmt.setString(1, "Park");
pstmt.setInt(2, 100);
int ret = pstmt.executeUpdate();
System.out.println("Return : " + ret );Return : 2
'Computer Language > JAVA' 카테고리의 다른 글
| [JAVA] 오버로딩, 오버라이딩 개념 및 차이점 파악하기 (0) | 2018.07.10 |
|---|---|
| [JAVA] currentTimeMillis, nanoTime 소스 수행 시간 차이 계산하기 (0) | 2018.06.28 |
| [JAVA] JSON 형식의 파일 읽어오기 (0) | 2018.06.27 |
| [JAVA] 멀티스레드 구현하기, Multi Thread 사용하기 (0) | 2018.06.27 |
| [JAVA] PreparedStatement 와 Statement 차이점 알아보기 (0) | 2018.01.26 |