从列中检索所有值

时间:2016-07-14 21:44:59

标签: java sql jdbc

如何通过SQL查询有效地从列中获取所有值,而无需在每次后续调用时连接到数据库?

我现在拥有的:

private List<String> retrieveSQLQuery(String sqlQuery) throws SQLException {
    JDBC jdbc = new JDBC();
    ResultSet rs = jdbc.getResultsSet(sqlQuery);
    List<String> values = new ArrayList<>();

    while (rs.next()) {
        values.add(rs.getString("model"));
    }
    return values;        
}

但是,对于每个后续的rs.next(),它会连接到数据库,创建一个语句然后检索该值。

看起来像这样:

Connecting to database... Creating statement... Statement Created. Connecting to database... Creating statement... Statement Created. value1 Connecting to database... Creating statement... Statement Created. Connecting to database... Creating statement... Statement Created. value2 Connecting to database... Creating statement... Statement Created. Connecting to database... Creating statement... Statement Created. value3

有更有效的方法吗?

编辑:

这是我的结果集方法:

public ResultSet getResultsSet(String QueryString) {
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        CachedRowSetImpl crs = null;
        try {
            // STEP 1: Register JDBC driver
            Class.forName(jdbcDriver);

            // STEP 2: Open a connection
            logger.info("Connecting to database...");
            conn = DriverManager.getConnection(dbUrl, user, password);

            // STEP 3: Execute a query.
            logger.info("Creating statement...");
            stmt = conn.createStatement();
            String sql;
            sql = QueryString;
            rs = stmt.executeQuery(sql);
            crs = new CachedRowSetImpl();
            crs.populate(rs);

            logger.info("Statement Created.");
            // STEP 5: Clean-up environment
        } catch (ClassNotFoundException e) {
            logger.error(e.getMessage());
        } catch (SQLException e) {
            logger.error(e.getMessage());
        } finally {
            try {
                if (rs != null) {
                    rs.close();
                }
            } catch (SQLException e) {
                logger.error(e.getMessage());
            }
            try {
                if (stmt != null) {
                    stmt.close();
                }
            } catch (SQLException e) {
                logger.error(e.getMessage());
            }
            try {
                if (conn != null) {
                    conn.close();
                }
            } catch (SQLException e) {
                logger.error(e.getMessage());
            }
        } // end try

        return crs;
    }

1 个答案:

答案 0 :(得分:3)

通过JDBC从DB检索数据的惯用方法是

  1. 获取Connection
  2. Statement
  3. 上创建Connection
  4. 执行Statement
  5. 迭代返回的Resultset
  6. 这意味着对于每个查询,您应该只检索一次Connection并创建一个Statement。请注意,每次检索Connection时都不应该连接到数据库;您应该从可用于JDBC的许多connection pools之一中检索它。另请注意,使用Class.forName(...)初始化驱动程序is redundant for post-JDBC 4.0 drivers

    简而言之,最好直接操作JDBC API类,而不是为这些类滚动自己的包装器/缓存。此外,StatementResultSet对象应具有非常有限的范围(意味着它们不应优先在方法之间传递),以防止资源泄漏。使用try-with-resources statement而不是遗留try-catch-finally结构,JDBC资源管理也是最好和最安全的。

    记住以上内容,重写retrieveSQLQuery()(仅使用JDBC API类,而不是自定义JDBC类)可能如下所示:

     public List<String> retrieveSQLQuery(String sqlQuery) throws SQLException {
    
        List<String> values = new ArrayList<>();
    
        try (Connection conn = DriverManager.getConnection(dbUrl, user, password);
                Statement statement = conn.createStatement();
                ResultSet rs = statement.executeQuery(sqlQuery)) {
    
            while (rs.next()) {
                // this assumes that the passed-in query string has 
                // a "model" column in the SELECT clause
                values.add(rs.getString("model"));
            }
        }
    
        return values;        
    }