Question

When reading across different posts a question came across the mind Where is prepared statement precompiled, in jvm or in db? And when does the process actually happen in a java class. Example Below :=

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;


public class PreparedStmtDemo {

public static void main(String args[]) throws SQLException,Exception {

    Class.forName("oracle.jdbc.driver.OracleDriver");
    Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:ORCL","scott","tiger");
    PreparedStatement preStatement = conn.prepareStatement("select RollNo from student where Stream =?");
    preStatement.setString(1, "Commerce");

    ResultSet result = preStatement.executeQuery();

    while(result.next()){
        System.out.println("Roll No: " + result.getString("RollNo"));
    }       
}

}

Was it helpful?

Solution

JDBC driver precompiles the PreparedStatement to a SQL statement which involves mapping parameters from Java data type to SQL data type.

Then the precompiled statement is pooled in the Oracle database.

PreparedStatement has the following advantages over normal Statement:

  • protection against SQL-injection attack
  • if you reuse the PreparedStatement instance in java with other parameters, JDBC driver wont need to precompile it again
  • Oracle database can reuse the pooled SQL statement

But if you don't use query parameters then Statement and PreparedStatement behave the same way.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top