Closing Resources Automatically - Java JDBC

Java examples for JDBC:Connection

Introduction

Use the try-with-resources syntax to automatically close the resources.

Demo Code

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class Main {
  public static void queryDatabase() {
    String qry = "select idber, recipe_name, description from recipes";

    try (Connection conn = getConnection();
        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery(qry);) {

      while (rs.next()) {
        String recipe = rs.getString("idBER");
        String name = rs.getString("RECIPE_NAME");
        String desc = rs.getString("DESCRIPTION");

        System.out.println(recipe + "\t" + name + "\t" + desc);
      }/* ww  w  .jav a2 s . c  om*/
    } catch (SQLException e) {
      e.printStackTrace();
    }
  }

  public static Connection getConnection() throws SQLException {
    Connection conn = null;
    String hostname = null;
    String port = null;
    String database = null;
    String username = null;
    String password = null;
    String driver = null;
    String jdbcUrl;
    if (driver.equals("derby")) {
      jdbcUrl = "jdbc:derby://" + hostname + ":" + port + "/" + database;
    } else {
      jdbcUrl = "jdbc:oracle:thin:@" + hostname + ":" + port + ":" + database;
    }
    conn = DriverManager.getConnection(jdbcUrl, username, password);
    System.out.println("Successfully connected");
    return conn;
  }
}

Related Tutorials