一、声明:
它用于访问您的数据库。 Statement 接口不能接受参数,当您在运行时使用静态 SQL 语句时很有用。如果您只想运行 SQL 查询一次,则该接口优于 PreparedStatement。
例子 –
//Creating The Statement Object
Statement GFG = con.createStatement();
//Executing The Statement
GFG.executeUpdate("CREATE TABLE STUDENT(ID NUMBER NOT NULL, NAME VARCHAR)");
2. 准备语句:
当您要多次使用 SQL 语句时使用它。 PreparedStatement 接口在运行时接受输入参数。
例子 –
//Creating the PreparedStatement object
PreparedStatement GFG = con.prepareStatement("update STUDENT set NAME = ? where ID = ?");
//Setting values to place holders
//Assigns "RAM" to first place holder
GFG.setString(1, "RAM");
//Assigns "512" to second place holder
GFG.setInt(2, 512);
//Executing PreparedStatement
GFG.executeUpdate();
CallableStatement 和 PreparedStatement 的区别:
Statement | PreparedStatement |
---|---|
It is used when SQL query is to be executed only once. | It is used when SQL query is to be executed multiple times. |
You can not pass parameters at runtime. | You can pass parameters at runtime. |
Used for CREATE, ALTER, DROP statements. | Used for the queries which are to be executed multiple times. |
Performance is very low. | Performance is better than Statement. |
It is base interface. | It extends statement interface. |
Used to execute normal SQL queries. | Used to execute dynamic SQL queries. |
We can not used statement for reading binary data. | We can used Preparedstatement for reading binary data. |
It is used for DDL statements. | It is used for any SQL Query. |
We can not used statement for writing binary data. | We can used Preparedstatement for writing binary data. |
No binary protocol is used for communication. | Binary protocol is used for communication. |