One thing that we need to do manually when programming using JDBC is to make sure to close all the resources that we use. All resources including the ResultSet
, Statement
and Connection
must be closed. This usually will produce a lot of boiler plate code in our program.
Starting from JDBC 4.1 which is a part of Java 7 we can use the try-with-resources
statement to automatically manage the resources that we use. This try statement closes the resources used when the block finishes its execution either normally or abruptly.
Here is an example that show us how to use the try-with-resources
statement.
package org.kodejava.example.jdbc;
import java.sql.*;
public class TryWithResourceJdbc {
private static final String URL = "jdbc:mysql://localhost/kodejava";
private static final String USERNAME = "root";
private static final String PASSWORD = "";
public static void main(String[] args) {
try (Connection conn =
DriverManager.getConnection(URL, USERNAME, PASSWORD);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM products")) {
while (rs.next()) {
String code = rs.getString("code");
String name = rs.getString("name");
System.out.println("Code: " + code + "; Name: " + name);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Maven dependencies
<!-- https://search.maven.org/remotecontent?filepath=mysql/mysql-connector-java/8.0.17/mysql-connector-java-8.0.17.jar -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.17</version>
</dependency>
Latest posts by Wayan (see all)
- How do I create a generic class in Java? - January 1, 2021
- How do I convert java.util.TimeZone to java.time.ZoneId? - April 25, 2020
- How do I get a list of all TimeZones Ids using Java 8? - April 25, 2020