栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

返回结果集

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

返回结果集

您永远不要

ResultSet
通过公共方法来回避。这很容易导致资源泄漏,因为您不得不保持语句和连接打开。关闭它们将隐式关闭结果集。但是,将它们保持打开状态将导致它们悬而未决,并且当它们打开过多时,将导致数据库用尽资源。

像这样将其映射到Javabeans的集合,并返回它:

public List<Biler> list() throws SQLException {    Connection connection = null;    PreparedStatement statement = null;    ResultSet resultSet = null;    List<Biler> bilers = new ArrayList<Biler>();    try {        connection = database.getConnection();        statement = connection.prepareStatement("SELECt id, name, value FROM Biler");        resultSet = statement.executeQuery();        while (resultSet.next()) { Biler biler = new Biler(); biler.setId(resultSet.getLong("id")); biler.setName(resultSet.getString("name")); biler.setValue(resultSet.getInt("value")); bilers.add(biler);        }    } finally {        if (resultSet != null) try { resultSet.close(); } catch (SQLException ignore) {}        if (statement != null) try { statement.close(); } catch (SQLException ignore) {}        if (connection != null) try { connection.close(); } catch (SQLException ignore) {}    }    return bilers;}

或者,如果您已经在使用Java 7,则只需使用try-with-
resources
语句即可自动关闭这些资源:

public List<Biler> list() throws SQLException {    List<Biler> bilers = new ArrayList<Biler>();    try (        Connection connection = database.getConnection();        PreparedStatement statement = connection.prepareStatement("SELECt id, name, value FROM Biler");        ResultSet resultSet = statement.executeQuery();    ) {        while (resultSet.next()) { Biler biler = new Biler(); biler.setId(resultSet.getLong("id")); biler.setName(resultSet.getString("name")); biler.setValue(resultSet.getInt("value")); bilers.add(biler);        }    }    return bilers;}

顺便说一句,你不应该声明

Connection
Statement
ResultSet
在所有的实例变量(主要threadsafety问题!),也被吞噬
SQLException
所有在这一点上(主叫方将不知道发生了问题),也被关闭资源相同
try
(例如,如果结果集close抛出异常,则语句和连接仍处于打开状态)。所有这些问题已在上述代码段中修复。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/432738.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号