First question for my first job in the industry, please be gentle.
I'm currently doing quite a lot of work with a MySQL database in Java using the java.sql library, working on code that was handed down to me. The existing way it handles executing an SQL statement comes in two varieties:
Connection connection = DriverManager.getConnection(...);
// code code code
Statement stmt = connection.createStatement();
ResultSet res = stmt.execute("SQL code here");
// code code code
stmt.close();
connection.close();
or
Connection connection = DriverManager.getConnection(...);
// code code code
ResultSet res = connection.createStatement().execute("SQL code here");
// code code code
connection.close()
The first option is much more common in the code I was given. A lot of different Statement objects being made for one or two queries and immediately closed.
The second option, at least to my eye, seems a lot cleaner and I would like to implement it, but I do worry that this does not close the Statement object being created. Would the second option actually cause any problems in terms of execution time, memory usage, etc. or would it actually improve/not change anything?
EDIT: the connection objects are being opened at the beginning of the program, stay open throughout, and close at the end.