在Java中传递结果集是否可能?

时间:2019-04-29 22:55:28

标签: java sql sqlite

我正在尝试执行一个命令,在该命令中我可以将不同的查询发送到SQLite / Mysql DB,并将结果集返回给正在调用的任何函数。它需要能够处理是2列还是15列。

下面的命令不起作用-大概是因为它关闭了结果集/连接,但是我不确定该怎么做。

有想法吗?

public static ResultSet queryDB(String query) {
    try {
        Connection connection = DriverManager.getConnection("jdbc:sqlite:" + Settings.SQLITE_DB_PATH);
        Statement statement = connection.createStatement();
        ResultSet resultSet = statement.executeQuery(query);
        resultSet.close();
        statement.close();
        connection.close();
        return resultSet;
    } catch (SQLException ex) {
        Logger.getLogger(SQLInterp.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}

1 个答案:

答案 0 :(得分:3)

您基本上有3个选择:

  1. 不要在方法中关闭ResultSetStatementConnection,将这样做的责任交还给调用者。

    不推荐,因为它容易出错,并且破坏了格式正确的代码结构范例。

  2. suggested by Jacob G.的形式传入具有处理数据所需逻辑的对象。

    例如使用Java 8+ Consumer

    public static void queryDB(String query, Consumer<ResultSet> processor) {
        try (
            Connection connection = DriverManager.getConnection("jdbc:sqlite:" + Settings.SQLITE_DB_PATH);
            Statement statement = connection.createStatement();
            ResultSet resultSet = statement.executeQuery(query);
        ) {
            processor.accept(resultSet);
        } catch (SQLException ex) {
            Logger.getLogger(SQLInterp.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    

    然后这样称呼它:

    SQLInterp.queryDB("SELECT * FROM foo", rs -> {
        while (rs.next()) {
            // process data here
        }
    });
    
  3. 以通用数据结构将所有数据读取到内存中,例如List<Map<String, Object>>

    这当然是假设查询的每一列都有很好的唯一名称。

    public static List<Map<String, Object>> queryDB2(String query) {
        try (
            Connection connection = DriverManager.getConnection("jdbc:sqlite:" + Settings.SQLITE_DB_PATH);
            Statement statement = connection.createStatement();
            ResultSet resultSet = statement.executeQuery(query);
        ) {
            ResultSetMetaData metaData = resultSet.getMetaData();
            int columnCount = metaData.getColumnCount();
            String[] name = new String[columnCount];
            for (int i = 0; i < columnCount; i++)
                name[i] = metaData.getColumnLabel(i + 1);
            List<Map<String, Object>> rows = new ArrayList<>();
            while (resultSet.next()) {
                Map<String, Object> row = new LinkedHashMap<>();
                for (int i = 0; i < columnCount; i++)
                    row.put(name[i], resultSet.getObject(i + 1));
                rows.add(row);
            }
            return rows;
        } catch (SQLException ex) {
            Logger.getLogger(SQLInterp.class.getName()).log(Level.SEVERE, null, ex);
        }
    }