猿问

在单个方法中重用连接对象

我遇到过这种模式。Connection当您需要执行多个 SQL 语句时,是否可以在单个方法中重用对象?


我最初的想法是在继续之前关闭所有资源:


Connection conn = null;

PreparedStatement ps = null;

ResultSet rs = null;

try {

    conn = ConnectionFactory.getConnection();

    ps = conn.prepareStatement("SELECT * FROM MYTABLE WHERE COL=?");

    ps.setString(1, "val");

    rs = ps.executeQuery();

    // get values used to determine the next statement type

} catch (SQLException e) {

    LOG.error("SQL failed.", e);

} finally {

    if(rs != null){rs.close();}

    if(ps != null){ps.close();}

    if(conn != null){conn.close();}

}

// Then another SQL statement is needed (either an UPDATE or INSERT).

// Repeat the same pattern to open, use and close the connection

执行以下操作是否同样安全?如果它是安全的,是否有真正的好处?


//... boilerplate

try {

    conn = ConnectionFactory.getConnection();

    ps = conn.prepareStatement("SELECT * FROM MYTABLE WHERE COL=?");

    ps.setString(1, "val");

    rs = ps.executeQuery();

    // ... more


    ps = conn.prepareStatement("UPDATE MYTABLE SET COL=?")

    // ... etc

} finally {

    if(rs != null){rs.close();}

    if(ps != null){ps.close();}

    if(conn != null){conn.close();}

}


皈依舞
浏览 157回答 2
2回答

弑天下

重用连接不是反模式,完全没问题。重用连接是在同一个本地 JDBC 事务中执行这两个语句的唯一方法。如果您正在编写访问关系数据库的应用程序,您应该了解事务。您实现异常处理的方式容易出错,因为如果在关闭任何资源时抛出异常,则后续资源不会关闭。如果关闭 PreparedStatement 引发异常,则连接不会关闭。try-with-resources 将是一种改进,但是try-with-resources 处理边缘情况的方式使我避免在 JDBC 中使用它,而是使用嵌套的 try-finally 块。如果这里有一个反模式,它是直接使用JDBC,它是非常低级的,涉及大量的剪切和粘贴,并且不容易使用事务或连接池。使用 Spring 将处理诸如划分数据库事务、使用连接池和关闭资源等细节。

鸿蒙传说

你应该做的是使用try-with-resources://... boilerplatetry (Connection conn = ConnectionFactory.getConnection()) {    try (PreparedStatement ps = conn.prepareStatement("SELECT * FROM MYTABLE WHERE COL=?")) {        ps.setString(1, "val");        try (ResultSet rs = ps.executeQuery()) {            // ... more        }    }    try (PreparedStatement ps = conn.prepareStatement("UPDATE MYTABLE SET COL=?")) {        // ... etc    }}
随时随地看视频慕课网APP

相关分类

Java
我要回答