Java – Prepared Statements along with Connection Pooling

connection-poolingjavajdbc

I have a question regarding general use of Prepared Statement along with connection pooling.

Prepared Statements are generally tied to one connection only.In our application, a PreparedStatement is created at the start up and executed at a later point.

If at the time of execution of some specific prepared statement, connection associated with the prepared statement is busy executing other statements than how this required statement will get executed.Does this statement will wait for connection to get free or this statement will be given preference in execution?

Update

I have tested this by following SLEEP() function with Apache derby database which calls java function sleep in class TimeHandlingTest.

CREATE FUNCTION SLEEP() RETURNS INTEGER LANGUAGE JAVA PARAMETER STYLE JAVA NO SQL EXTERNAL NAME 'com.derby.test.TimeHandlingTest.sleep';

And made two prepared statements from one connection and called Sleep() function from one prepared statement and simple sql select with other.Simple sql select took almost same time(10s) for which first prepared statement was sleeping.This means that one connection object cannot be used for execution by more than one prepared statement at a time.Please correct me if i am wrong.

Best Answer

You can't return the Connection to the pool if you plan on using the PreparedStatement.

In other words: you can only use a PreparedStatement constructed from a Connection that you currently have.