Master java skills

JDBC Prepared Statement

The JDBC API provides Statement object to execute queries, updates, and DDL statements on data in a database. The PreparedStatement is subclass of` Statement that provides better security, portability across vendors, and performance.

SQL command used in a PreparedStatement is pre-compiled or prepared initially and then reused.

PreparedStatement is precompiled

What does pre-compile mean? When we run an SQL command on the database, the database will first validate, parse, and build an execution plan to run it. These steps fall under pre-compiling stage.

When the JDBC driver creates a prepared statement, it asks the database to pre-compile that SQL command. Then, the database will store the pre-compiled command in a cache for the current database connection. If the same SQL command is to be run multiple times, using the pre-compiled version is better for performance since the compilation part has to be done only once.

The database has a limited cache for pre-compiled SQL commands and hence, we cannot have too many of them. Defining parameters helps make the command reusable and therefore reduces the number of distinct commands.

Let’s see one example. We will insert some records here using PreparedStatement

package core_java_project;

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

public class PreparedStatementExample {

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

		//Loading the driver
		Class.forName("com.mysql.cj.jdbc.Driver");

		Connection con = null;

		// Step 2 : Getting Connection Object
		con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test_db", "root", "abcd");
		
		PreparedStatement stmt = con.prepareStatement("insert into doctor values(?,?,?)");

		stmt.setInt(1, 102);
		stmt.setString(2, "Cardiology");
		stmt.setString(3, "Dr Rahul");

		stmt.execute();
		
		stmt.setInt(1, 103);
		stmt.setString(2, "Dermatology");
		stmt.setString(3, "Dr Venkat");

		stmt.execute();
		
		System.out.println("Data inserted successfully.");
		
	}
}
Output:
Data inserted successfully.

In the database

Difference between Statement and PreparedStatement

FeatureStatementPreparedStatement
DefinitionIt is used to run static queriesIt is used to run precompiled queries
Query CompilationCompiled each time the query is executedCompiled once and can be executed multiple times with different parameters
PerformanceLess efficient for repeated queriesMore efficient for repeated queries due to pre-compilation
ReusabilityLess reusable for different inputsHighly reusable with different parameter values
Use CaseSuitable for simple and ad-hoc queriesSuitable for complex queries and batch processing.
Error HandlingErrors in syntax are detected at run timeErrors in syntax are detected at compile time
SQL InjectionMore prone to sql injection attacksLess prone due to parameter binding