I currenctly have a class which does several requests to a database with several methods (called from main method) sharing this pattern :
public int getSomething(String id, File file) {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
int lines = 0;
try {
conn = openConnection();
ps = conn.prepareStatement(SQL_QUERY.replace("?", id));
ps.setFetchSize(1500);
rs = ps.executeQuery();
lines += nnpw.writeInFile(file, rs);
} catch (Exception e) {
e.printStackTrace();
} finally {
close(rs, ps, conn);
}
return lines;
}
The method openConnection()
is in the main class and looks like this :
protected Connection openConnection() throws SQLException, ClassNotFoundException {
Class.forName(jdbcParams.getString("jdbc.driver"));
Connection connect;
connect = DriverManager.getConnection(jdbcParams.getString("jdbc.url"), //$NON-NLS-1$
jdbcParams.getString("jdbc.username"), //$NON-NLS-1$
jdbcParams.getString("jdbc.password")); //$NON-NLS-1$
return connect;
}
Would it be better if I had a Connection
parameter in the main class, which I would open and close like this, and modify the close(rs, ps, conn)
from above to close(rs, ps)
?
public MainClass {
Connection conn;
public static void main(String[] args) {
try {
int lines = 0;
DBExtract ex = new DBExtract();
...
conn = openConnection()
lines += ex.getSomething("1", file, conn);
lines += ex.getSomethingElse("1", file, conn);
lines += ex.getSomethingDifferent("1", file, conn);
conn.close()
} catch(Exception e) {
e.printStackTrace();
}
}
}