Computer >> 컴퓨터 >  >> 프로그래밍 >> MySQL

JDBC의 execute(), executeQuery(), executeUpdate() 메서드 차이점 완벽 정리

JDBC에서 Statement 객체를 생성한 후에는 Statement 인터페이스가 제공하는 세 가지 실행 메서드 중 하나를 사용해 SQL 문을 실행할 수 있습니다. 바로 execute(), executeUpdate(), executeQuery()입니다.

세 메서드는 각각 용도와 반환값이 다르기 때문에, 실행하려는 SQL 문의 종류에 맞게 적절한 메서드를 선택하는 것이 중요합니다. 아래에서 각 메서드의 특징과 사용 예제를 살펴보겠습니다.

1. execute() 메서드

execute() 메서드는 주로 SQL DDL(Data Definition Language) 문, 즉 CREATE TABLE, ALTER TABLE, DROP TABLE 같은 문장을 실행할 때 사용합니다. 이 메서드는 boolean 값을 반환하며, 그 결과가 true이면 ResultSet 객체를 가져올 수 있음을 의미하고, false이면 결과 집합이 없음을 나타냅니다.

예제 코드

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class Example {
    public static void main(String args[]) throws SQLException {
        // 드라이버 등록
        DriverManager.registerDriver(new com.mysql.jdbc.Driver());
        // 연결 생성
        String mysqlUrl = "jdbc:mysql://localhost/sampleDB";
        Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
        System.out.println("Connection established......");
        // Statement 생성
        Statement stmt = con.createStatement();

        // 문장 실행
        String createTable = "CREATE TABLE Employee( "
            + "Name VARCHAR(255), "
            + "Salary INT NOT NULL, "
            + "Location VARCHAR(255))";
        boolean bool = stmt.execute(createTable);

        System.out.println(bool);
    }
}

실행 결과

Connection established......
false

DDL 문은 데이터를 조회하지 않기 때문에 결과가 false로 출력됩니다.

2. executeUpdate() 메서드

executeUpdate() 메서드는 INSERT, UPDATE, DELETE와 같이 데이터를 변경하는 DML 문을 실행할 때 사용합니다. 이 메서드는 int 타입의 정수를 반환하며, 이 값은 SQL 문에 의해 영향을 받은 행(row)의 개수를 의미합니다.

예제 코드

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class ExecuteUpdateExample {
    public static void main(String args[]) throws SQLException {
        // 드라이버 등록
        DriverManager.registerDriver(new com.mysql.jdbc.Driver());
        // 연결 생성
        String mysqlUrl = "jdbc:mysql://localhost/sampleDB";
        Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
        System.out.println("Connection established......");
        // Statement 생성
        Statement stmt = con.createStatement();

        String insertData = "INSERT INTO Employee("
            + "Name, Salary, Location) VALUES "
            + "('Amit', 30000, 'Hyderabad'), "
            + "('Kalyan', 40000, 'Vishakhapatnam'), "
            + "('Renuka', 50000, 'Delhi'), "
            + "('Archana', 15000, 'Mumbai')";

        int i = stmt.executeUpdate(insertData);
        System.out.println("Rows inserted: "+i);
    }
}

실행 결과

Connection established......
Rows inserted: 4

4개의 행이 삽입되었으므로 반환값으로 4가 출력됩니다.

3. executeQuery() 메서드

executeQuery() 메서드는 SELECT 문처럼 표 형태의 데이터를 반환하는 SQL 문을 실행할 때 사용합니다. 이 메서드는 ResultSet 클래스의 객체를 반환하며, 이 객체를 통해 조회된 데이터를 행 단위로 순회하며 읽을 수 있습니다.

예제 코드

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class ExecuteQueryExample {
    public static void main(String args[]) throws SQLException {
        // 드라이버 등록
        DriverManager.registerDriver(new com.mysql.jdbc.Driver());
        // 연결 생성
        String mysqlUrl = "jdbc:mysql://localhost/sampleDB";
        Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
        System.out.println("Connection established......");
        // Statement 생성
        Statement stmt = con.createStatement();

        // 데이터 조회
        ResultSet rs = stmt.executeQuery("Select *from Employee");

        while(rs.next()) {
            System.out.print("Name: "+rs.getString("Name")+", ");
            System.out.print("Salary: "+rs.getInt("Salary")+", ");
            System.out.print("City: "+rs.getString("Location"));
            System.out.println();
        }
    }
}

실행 결과

Connection established......
Name: Amit, Salary: 30000, City: Hyderabad
Name: Kalyan, Salary: 40000, City: Vishakhapatnam
Name: Renuka, Salary: 50000, City: Delhi
Name: Archana, Salary: 15000, City: Mumbai

세 메서드 비교 요약

메서드주요 용도반환값
execute()DDL 문 (CREATE, ALTER, DROP 등)boolean (ResultSet 존재 여부)
executeUpdate()DML 문 (INSERT, UPDATE, DELETE)int (영향 받은 행의 수)
executeQuery()조회 문 (SELECT)ResultSet 객체

정리하면, 테이블 구조 변경에는 execute(), 데이터 삽입·수정·삭제에는 executeUpdate(), 데이터 조회에는 executeQuery()를 사용하는 것이 JDBC 프로그래밍의 기본 원칙입니다. 각 메서드의 반환값을 적절히 활용하면 SQL 실행 결과를 보다 명확하게 처리할 수 있습니다.