Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Question on Prepared Statement in Java

Tags:

database

jdbc

We have a Prepared Statement in Java and we hear that it is different from Statement in the Way that this prepared statement need not be compiled every time it is used.

My question is where is this Compiled Statement stored ? In the Client code that uses it or is it stored by the Database ?

Why would a DB Store a Compiled statement and if it does than for how long ?

like image 788
Geek Avatar asked Feb 24 '26 06:02

Geek


1 Answers

Databases have a query cache, which means that when you execute a query the database caches the parsed/compiled query and maybe the query plan to eliminate future computations.

The prepared statements are typically cached first at the application level, where the application container is responsible for managing the statements cache. Most application containers have options to control the prepared statements cache (eg: glassfish).

As you can see here, the main difference is like you stated: with prepared statements, the application reduce the cost of compiling the same statement over and over. As a side note, for most app containers the statement must be exactly the same (whitespace included) in order to be reused correctly, so be careful when using hand-written queries.

like image 115
Miguel Ping Avatar answered Feb 27 '26 01:02

Miguel Ping



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!