Reputation: 44041
Specifically if I have three queries should I do
PreparedStatement singleQuery ...
and "share" the one object. Or should I do
PreparedStatement query1 ...
PreparedStatement query2 ...
PreparedStatement query3 ...
Upvotes: 1
Views: 1024
Reputation: 3947
If the queries are different, you probably need separate PreparedStatement s but if the different queries can be handled by one parameterized query, you should probably go that route.
Upvotes: 2
Reputation: 15940
You can use it any way, there is NO performance issue as long as you open the Prepared statement and Close the prepared Statements appropriately.
Suppose if you use the single prepared Statements, Make sure if you are going to use that one for the second one, the required variables to be provided appropriately.
Upvotes: 0
Reputation: 54276
It depends on how different the three queries are. If they are the same query but with different arguments then use a single PreparedStatement
and set the arguments each time. If they are essentially three different queries (e.g. a select followed by an update) then you'll need three different PreparedStatement
s.
For example, if the SQL for all three is of the form SELECT * FROM table WHERE id = something
then a single statement is fine.
If the first query is SELECT name FROM customers WHERE id = ?
and the second is SELECT price FROM products WHERE id = ?
then you're gonna need different objects.
Upvotes: 5
Reputation: 14786
Generally you would use a separate PreparedStatement object for each query; that way you could keep them around to re-use, potentially saving preparation overhead.
If you aren't planning to re-use your statements, though, it probably doesn't matter.
Upvotes: 1
Reputation: 162761
Use a single parameterized query and call it 3 times, each time binding the new parameter values. If your db supports caching of prepared statements, you'll get better performance because the actual query will only need to be compiled once by the RDBMS.
Upvotes: 1
Reputation: 262464
If the three queries use the same SQL, reuse the same object.
If not, have three separate objects.
Do not share the same object across multiple threads.
Upvotes: 3