Is it good practice to return PreparedStatement from a utility?

I am working on an inherited large base of Java code, where many disparate methods make database queries in insanely different ways; since I am debugging and standardizing everything, most of the code I write is as follows:

log.info("Audit-required logging for query: "+SOME_QUERY);
log.info("Ditto for each argument: "+parameter+" "+otherParameter+ ...);
ps = conn.prepareStatement(SOME_QUERY);
ps.setString(1, aString);
ps.setString(2, anotherString);
// ... 
ps.setString(14, yetAnotherString);
rs = ps.executeQuery();
log.debug("Query executed: "+SOME_QUERY);

I hate that I need to write the request three times and the parameters twice (plus doing setString () for each) - this is a recipe for future errors when performing maintenance. I would prefer to place all this inside a (static) universal method that would allow me to simply say everything once (plus future proof of the code base, if some other action is necessary ... like, say, another legal department requires some either logging, or a new kind of error handling is required). Something like that:

public static PreparedStatement fullyPrepare(final Connection conn, final String query, final String... arguments) { ... }

which I would then call with one sentence (instead of the entire code block every time):

ps = fullyPrepare(conn, CONSTANT_FOR_THIS_QUERY, parameter, otherParameter, ...);

, , , , " ". , , , PreparedStatement , , ( , , ResultSet, ResultSet?).

PreparedStatement ?

+4
2

.

? PrepareStatement . . , .

, . DbUtils, jdbc-helper jDBI . jcabi-jdbc, JOOQ. , (jdbc- ), .

, , , , null (Oracle, !). , , jDBI - , , .

+3

PreparedStatement Connection, , , .

. : PreparedStatement ?

+2

Source: https://habr.com/ru/post/1668530/


All Articles