Handling Connection and SQL Exceptions with a try-catch block to capture and handle any SQL exceptions - Java JDBC

Java examples for JDBC:SQL Warning

Description

Handling Connection and SQL Exceptions with a try-catch block to capture and handle any SQL exceptions

try { 
    // perform database tasks 
} catch (java.sql.SQLException){ 
   // perform exception handling 
} 

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 main(String[] args) {
    String qry = "select id, name, description from recipes";
    try (Connection conn = getConnection();
        Statement stmt = conn.createStatement();) {
      ResultSet rs = stmt.executeQuery(qry);
      while (rs.next()) {
        // PERFORM SOME WORK
      }//w w  w.j a  v  a2s . c o  m
    } 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 jndi = 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