PreparedStatment ps = null;
public void executeQueries(){
try{
ps = conn.prepareStatement(Query1);
// Execute Query1 here and do the processing.
ps = conn.prepareStatement(Query2);
// Execute Query2 here and do the processing.
//... more queries
}catch(){}
finally{
ps.close(); // At this point would the caching of queries in DB be lost?
}
}
In my Application, I call the method executeQueries()
frequently.
My question is, If I close the PreparedStatement
in the finally block inside the method (that I use frequently), would the database system remove the caching? If YES, can I make a global PreparedStatement
for the entire application as there are loads of JAVA CLASSES in my application that query the database.
Thank you!
Update : The question has been marked duplicate but the linked thread does not answer my question at all. AFAIK, the database system stores the executed queries in the cache memory. It also stores their execution plan. This is where PreparedStatement
perfoms better than Statement
. However, I am not very sure if the information related to the query is removed once the PreparedStatement
is closed.
Specifically with regard to MySQL, according to
8.10.3 Caching of Prepared Statements and Stored Programs
The server maintains caches for prepared statements and stored programs on a per-session basis. Statements cached for one session are not accessible to other sessions. When a session ends, the server discards any statements cached for it.
So closing a PreparedStatement
would not remove the statement(s) from the cache, but closing the Connection
presumably would.
... unless the application uses a connection pool, in which case closing the Connection
may not necessarily end the database session; it may keep the session open and just return the connection to the pool.
Then there's also the question of whether the statements are actually being PREPAREd on the server. That is controlled by the useServerPrepStmts
connection string attribute. IIRC, by default, server-side prepared statements are not enabled.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With