Statement 인터페이스는 정적 SQL 구문을 표현하며, Java 프로그램에서 범용적인 SQL 문장을 생성하고 실행하는 데 사용됩니다. JDBC에서 데이터베이스로 SQL을 전달하는 가장 기본적인 방식으로, PreparedStatement나 CallableStatement와 달리 SQL 문자열을 매번 그대로 데이터베이스에 전송합니다.
Statement 객체 생성하기
Connection 인터페이스의 createStatement() 메서드를 호출하면 Statement 객체를 생성할 수 있습니다. 아래와 같이 이 메서드를 호출하여 Statement를 만듭니다.
Statement stmt = null;
try {
stmt = conn.createStatement();
. . .
}
catch (SQLException e) {
. . .
}
finally {
. . .
}
Statement 객체 실행하기
Statement 객체를 생성한 후에는 execute(), executeUpdate(), executeQuery() 중 하나의 execute 계열 메서드를 사용하여 실행할 수 있습니다. 각 메서드의 역할은 다음과 같습니다.
execute(): CREATE, ALTER, DROP 같은 SQL DDL 문을 실행하는 데 사용되며, ResultSet 객체를 가져올 수 있는지 여부를 나타내는 boolean 값을 반환합니다.
executeUpdate(): INSERT, UPDATE, DELETE 같은 문장을 실행하는 데 사용되며, 영향을 받은 행의 수를 나타내는 정수 값을 반환합니다.
executeQuery(): SELECT 문처럼 표 형태의 데이터를 반환하는 문장을 실행하는 데 사용되며, ResultSet 클래스의 객체를 반환합니다.
예제
다음 JDBC 애플리케이션은 Statement를 생성하고 실행하는 과정을 보여줍니다. 드라이버를 등록하고 데이터베이스에 연결한 뒤, 테이블 생성·데이터 삽입·조회를 차례로 수행합니다.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class StatementExample {
public static void main(String args[]) throws SQLException {
// 드라이버 등록
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
// 데이터베이스 연결 가져오기
String mysqlUrl = "jdbc:mysql://localhost/testdb";
Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
System.out.println("Connection established......");
// Statement 생성
Statement stmt = con.createStatement();
// Statement 실행 - 테이블 생성
String createTable = "CREATE TABLE Employee("
+ "Name VARCHAR(255), "
+ "Salary INT NOT NULL, "
+ "Location VARCHAR(255))";
boolean bool = stmt.execute(createTable);
// Statement 실행 - 데이터 삽입
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);
// Statement 실행 - 데이터 조회
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...... Rows inserted: 4 Name: Amit, Salary: 30000, City: Hyderabad Name: Kalyan, Salary: 40000, City: Vishakhapatnam Name: Renuka, Salary: 50000, City: Delhi Name: Archana, Salary: 15000, City: Mumbai
마무리 및 참고 사항
Statement는 간단한 일회성 SQL 실행에 적합하지만, 실제 운영 환경에서는 SQL 인젝션 공격을 방지하고 반복 실행 시 성능을 높이기 위해 매개변수화된 쿼리를 지원하는 PreparedStatement를 사용하는 것이 권장됩니다. 또한 사용이 끝난 Statement와 ResultSet은 finally 블록이나 try-with-resources 구문을 통해 반드시 닫아야 리소스 누수를 예방할 수 있습니다.