I have the following Query class with 2 methods, insert()
method is used frequently and deleteRecord()
is not.
public class Query1 {
private final static String INSERT = "insert into info values (?, current_timestamp)";
private final static String DELETE_RECORD = "delete from info where stamp = ?";
private static final Connection con = DatabaseConnection.getInstance();
//This method is used frequently
public static void insert(List<String> numList) throws SQLException {
try (PreparedStatement st_insert = con.prepareStatement(INSERT)) {
for (int i = 0; i < numList.size(); i++) {
st_insert.setString(1, numList.get(i));
st_insert.addBatch();
}
st_insert.executeBatch();
}
}
// This method is NOT used frequently
public static void deleteRecord(Timestamp stamp) throws SQLException {
try (PreparedStatement st = con.prepareStatement(DELETE_RECORD)) {
st.setTimestamp(1, stamp);
st.execute();
}
}
I converted Query1 class to below in which the PreparedStatement used by the insert()
method is initialized in the static block since it's frequently used.
public class Query2 {
private final static String INSERT = "insert into info values (?, current_timestamp)";
private final static String DELETE_RECORD = "delete from info where stamp = ?";
private static final Connection con = DatabaseConnection.getInstance();
// Frequently used statements
private static PreparedStatement st_insert;
static {
try {
st_insert = con.prepareStatement(INSERT);
} catch (SQLException ex) {
}
}
//This method is used frequently
public static void insert(List<String> numList) throws SQLException {
for (int i = 0; i < numList.size(); i++) {
st_insert.setString(1, numList.get(i));
st_insert.addBatch();
}
st_insert.executeBatch();
}
// This method is NOT used frequently
public static void deleteRecord(Timestamp stamp) throws SQLException {
try (PreparedStatement st = con.prepareStatement(DELETE_RECORD)) {
st.setTimestamp(1, stamp);
st.execute();
}
}
Does this optimize the code considering the use of prepared statements or is this not a good practice? if not how to do it? (I'm a beginner to JDBC and haven't come across any code examples like this.)
Any suggestions would be greatly appreciated.