【问题标题】:Alternative to ResultSet for storing data from databaseResultSet 的替代方法,用于存储数据库中的数据
【发布时间】:2015-02-25 19:53:51
【问题描述】:

我有一个数据库,目前我正在使用 PreparedStatement 使用 SQL 语句从数据库中调用数据。但是我知道一旦 PreparedStatement 完成,ResultSet 就会关闭。

我需要一个替代方法(结果集关闭),因为每次用户单击按钮时都会运行 Prepared Statement,并且 Prepared Statement 的输入可以更改,但是 ResultSet 不能采用任何新值。

任何想法将不胜感激。

【问题讨论】:

    标签: java sql jdbc prepared-statement resultset


    【解决方案1】:

    您应该在关闭PreparedStatement 之前将数据从ResultSet 复制到您自己的对象中。

    例如:

    preparedStatement = conn.prepareStement("select * from people");
    
    resultSet = preparedStatement.executeQuery();
    
    //copying the value
    while(resultSet.hasNext()){
        String name = resultSet.getString("name");
        String surname = resultSet.getString("surname");
    
        //Person is a class of your own
        Person person = new Person(name,surname); 
    
        //people is a Collection of Person created outside this loop
        people.add(person); 
    }
    

    之后,确保关闭 finnally 块中的 PreparedStatement,并使用 people 集合中的对象,而不是直接使用 ResultSet

    【讨论】:

    • 对不起,我不太明白你的最后一点 people.add(person)。您如何使 person 成为 Person 类的集合。
    • 我将“人”(而不是“人”)设为人的集合。你可以用Collection<Person> people = new LinkedList<Person>();
    猜你喜欢
    • 1970-01-01
    • 2020-09-06
    • 2014-11-18
    • 2013-02-16
    • 1970-01-01
    • 2019-05-10
    • 2011-04-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多