I want to use prepared statements. I have read that the advantage of prepared statements is that they don't have to be parsed/compiled every time again so one reduces load. Now my question is, where the "recognition" of an already prepared statement takes place, in Java or within my DB system? I ask, because I want to know where to store my PreparedStatement object in my code: as class attribute and set the parameters with every request OR create a new prepared statement object whenever there is a request.
public class Option1 {
private PreparedStatement myStatement;
public Option1() {
// create the myStatement object
myStatement = conn.prepareStatement("");
}
public List<Items> query() {
// just use the myStatement object
myStatement.setString(1, "foo");
}
}
public class Option2 {
public List<Items> query() {
PreparedStatement myLocalStatement = conn.prepareStatement("");;
// create and use the statement
myLocalStatement.setString(1, "foo");
}
}
Now my question is, what is the better way to do it, option 1 or 2? However, I have to do a "cleanup" after every execution by doing a myStatement.close()
right?
Maybe I should ask it in another way: how to reuse it in the most effective way?
UPDATE: in the case there are two answers, one prefering option 1 and one option 2, I would kindly ask the community to vote for their choice ^^