statement로 db에 쿼리를 집어 넣는 함수 중, 크게 세가지가 있었다.
Execute :
1. 수행결과로 Boolean 타입의 값을 반환합니다.
2. 모든 구문을 수행할 수 있습니다.
리턴값이 ResultSet인 경우에는 true, 그 외에는 false로 출력됨.
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);
Result : true
ExecuteQuery
1. 수행결과로 ResultSet 객체의 값을 반환합니다.
2. SELECT 구문을 수행할 때 사용되는 함수입니다.
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
2인 이유 : NAME, ID 2개의 레코드가 변했기 때문
--> 잘 쿼리가 작성되었는지 확인하려면,
executeQuery 이후.
if(rs.next()) {
//쿼리가 수행된 후
}
식으로 수행하거나,
executeUpdate 이후,
그 반환값이 0 이상이거나.. 라는 식으로 처리하면 될 것같다.
'TIL' 카테고리의 다른 글
[java] Pattern, Matcher (0) | 2022.12.20 |
---|---|
오라클 MERGE문 (0) | 2022.12.16 |
ResultSet (0) | 2022.12.13 |
면접준비 쪼금만 (0) | 2022.12.02 |
getby vs findby vs existby (0) | 2022.11.25 |