【问题标题】:The correct way to get/close DataSource connection获取/关闭 DataSource 连接的正确方法
【发布时间】:2015-06-08 19:17:12
【问题描述】:

我正在 eclipse 上开发一个动态 web 项目。

以下是使用 DataSource 连接 MySQL 的示例。 这是正确的方法吗?我的意思是在 Servlet 中获得连接是否正常?

此外,我发现这种获取/关闭连接的方式很乏味,因为每次想要获取/关闭连接时,我都需要编写完全相同的代码部分。我认为应该有更好的方法。有人可以给我一些建议吗?

谢谢!

@WebServlet(name="HelloUser", urlPatterns={"/hellouser"})
public class HelloUserServlet extends HttpServlet{
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {

            DataSource ds = MyDataSourceFactory.getMySQLDataSource();
            Connection con = null;
            Statement stmt = null;
            ResultSet rs = null;
            try {
                con = ds.getConnection();
                stmt = con.createStatement();
                rs = stmt.executeQuery(...);
                ...
            } catch (SQLException e) {
                e.printStackTrace();
            }finally{
                    try {
                        if(rs != null) rs.close();
                        if(stmt != null) stmt.close();
                        if(con != null) con.close();
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
            }
        }
    }
}

【问题讨论】:

  • 简答:否。长回答:首先了解try-with-resources 构造,其次考虑了解更高级别的JDBC 库,例如Spring JDBC
  • 谢谢!我会试试 Spring JDBC。

标签: java mysql jdbc datasource


【解决方案1】:

从 Java 7 开始,您可以使用try-with-resource(更新了 JDBC api 以实现 Autocloseable)。

try-with-resources 语句是一个 try 语句,它声明一个 或更多资源。资源是必须在之后关闭的对象 程序结束了

例如

try (Connection con = ds.getConnection();
    Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(...)) {...}

【讨论】:

    最近更新 更多