我环顾四周,但似乎找不到我的问题的答案.
I have looked around, but can't seem to find the answer to my question.
这是上下文:我必须连接到Java程序中的数据库,并执行一个我无法控制且事先不知道的SQL请求.为此,我使用下面的代码.
Here is the context : I have to connect to a Database in my Java program and execute a SQL request that I have no control over and don't know in advance. To do that I use the code below.
public Collection<HashMap<String, String>> runQuery(String request, int maxRows) { List<HashMap<String, String>> resultList = new ArrayList<>(); DataSource datasource = null; try { Context initContext = new InitialContext(); datasource = (DataSource) initContext.lookup("java:jboss/datasources/xxxxDS"); } catch (NamingException ex) { // throw something. } try (Connection conn = datasource.getConnection(); Statement statement = conn.createStatement(); ResultSet rs = statement.executeQuery(request); ) { while (rs.next()) { HashMap<String, String> map = new HashMap<>(); for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) { map.put(rs.getMetaData().getColumnName(i).toUpperCase(), rs.getString(i)); } resultList.add(map); } } catch (SQLException ex) { // throw something. } return resultList; }我面临的问题是:如您所见,还有另一个我不使用的参数maxRows.我需要将其指定给statement,但不能在try-with-resources中执行.
The issue I am facing is : As you can see there is another parameter maxRows that I don't use. I need to specify this to the statement but can't do it in the try-with-resources.
我想通过在第一个内部嵌套另一个try-with-resources以便指定最大行数来避免这种方法的认知复杂性(例如在此代码示例中).
I would like to avoid increasing cognitive complexity of this method by nesting another try-with-resources inside the first one in order to specify the max number of rows (like in this sample of code).
try (Connection conn = datasource.getConnection(); Statement statement = conn.createStatement(); ) { statement.setMaxRows(maxRows); try (ResultSet rs = statement.executeQuery(request); ) { while (rs.next()) { HashMap<String, String> map = new HashMap<>(); for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) { map.put(rs.getMetaData().getColumnName(i).toUpperCase(), rs.getString(i)); } resultList.add(map); } } } catch (SQLException ex) { // throw something. }有什么办法可以只用一个try-with-resources吗?
Is there any way to do it with only one try-with-resources?
推荐答案如果您可以选择其他方法,那么仅需使用一个try-resources即可.
If you are fine to go for an additional method then it can be possible with only one try-resources
代替Statement statement = conn.createStatement();
Statement statement = createStatement(conn, maxRows);
在该新方法中,创建Statement对象并设置maxRows并返回语句obj.
Inside that new method, create Statement object and set the maxRows and return the statement obj.
更多推荐
如何在数据库连接中正确使用try
发布评论