Statement 인터페이스는 정적 SQL 문을 나타내며 Java 프로그램을 사용하여 범용 SQL 문을 생성하고 실행하는 데 사용됩니다.
명세서 작성
createStatement()를 사용하여 이 인터페이스의 개체를 만들 수 있습니다. 연결 방법 상호 작용. 아래와 같이 이 메서드를 호출하여 문을 만듭니다.
Statement stmt = null;
try {
stmt = conn.createStatement( );
. . .
}
catch (SQLException e) {
. . .
}
finally {
. . .
} Statement 개체 실행
명령문 개체를 생성한 후에는 execute(), executeUpdate() 및 executeQuery()와 같은 실행 메서드 중 하나를 사용하여 실행할 수 있습니다.
-
실행(): 이 메서드는 SQL DDL 문을 실행하는 데 사용되며 ResultSet 개체를 검색할 수 있는 날씨를 지정하는 부울 값을 반환합니다.
-
업데이트 실행(): 이 메소드는 삽입, 업데이트, 삭제와 같은 명령문을 실행하는 데 사용됩니다. 영향을 받는 행 수를 나타내는 정수 값을 반환합니다.
-
실행 쿼리(): 이 메서드는 테이블 형식 데이터를 반환하는 문을 실행하는 데 사용됩니다(예제 SELECT 문). ResultSet 클래스의 객체를 반환합니다.
예시
다음 JDBC 응용 프로그램은 문을 만들고 실행하는 방법을 보여줍니다.
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 {
//Registering the Driver
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
//Getting the connection
String mysqlUrl = "jdbc:mysql://localhost/testdb";
Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
System.out.println("Connection established......");
//Creating the Statement
Statement stmt = con.createStatement();
//Executing the statement
String createTable = "CREATE TABLE Employee(“
+ "Name VARCHAR(255), "
+ "Salary INT NOT NULL, "
+ "Location VARCHAR(255))";
boolean bool = stmt.execute(createTable);
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);
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