📜  PreparedStatement 和 CallableStatement 的区别

📅  最后修改于: 2021-09-15 02:02:20             🧑  作者: Mango

1. 可调用语句:
当您要使用数据库存储过程时使用它。 CallableStatement 可以接受运行时输入参数。

例子 –

//Creating CallableStatement object 
CallableStatement GFG = con.prepareCall("{call anyProcedure(?, ?, ?)}");
 
//Use GFG.setter() methods to pass IN parameters
 
//Use GFG.registerOutParameter() method to register OUT parameters
 
//Executing the CallableStatement
 GFG.execute();
 
//Use GFG.getter() methods to retrieve the result 

2. 准备语句:
当您要多次使用 SQL 语句时使用它。 PreparedStatement 接口在运行时接受输入参数。

例子 –

//Creating the PreparedStatement object 
PreparedStatement GFG = con.prepareStatement("update STUDENT set NAME = ? where ID = ?");
  
//Setting values to place holders  
GFG.setString(1, "RAM");   //Assigns "RAM" to first place holder
          
GFG.setInt(2, 512);     //Assigns "512" to second place holder
 
//Executing PreparedStatement
GFG.executeUpdate(); 

CallableStatement 和 PreparedStatement 的区别:

CallableStatement PreparedStatement
It is used when the stored procedures are to be executed. It is used when SQL query is to be executed multiple times.
You can pass 3 types of parameter IN, OUT, INOUT. You can pass any type of parameters at runtime.
Used to execute functions. Used for the queries which are to be executed multiple times.
Performance is very high. Performance is better than Statement.
Used to call the stored procedures. Used to execute dynamic SQL queries.
It extends PreparedStatement interface. It extends Statement Interface.
No protocol is used for communication. Protocol is used for communication.