Closing Database Connections in Java

前端 未结 6 1326
小鲜肉
小鲜肉 2020-11-22 09:34

I am getting a little confused, I was reading the below from http://en.wikipedia.org/wiki/Java_Database_Connectivity

Connection conn = DriverManager.getConn         


        
6条回答
  •  一整个雨季
    2020-11-22 10:34

    Actually, it is best if you use a try-with-resources block and Java will close all of the connections for you when you exit the try block.

    You should do this with any object that implements AutoClosable.

    try (Connection connection = getDatabaseConnection(); Statement statement = connection.createStatement()) {
        String sqlToExecute = "SELECT * FROM persons";
        try (ResultSet resultSet = statement.execute(sqlToExecute)) {
            if (resultSet.next()) {
                System.out.println(resultSet.getString("name");
            }
        }
    } catch (SQLException e) {
        System.out.println("Failed to select persons.");
    }
    

    The call to getDatabaseConnection is just made up. Replace it with a call that gets you a JDBC SQL connection or a connection from a pool.

提交回复
热议问题