Tuesday, August 5, 2014

JDBC: Catching all exceptions!

JDBC is notorious for its checked exception
java.sql.SQLException
. Here is a sample explaining all the exception catching and boiler plate (and the mess):
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class InsertCatchDemo {
  public static void main(String[] args) {
    Connection conn = null;
    try {
      conn = DriverManager.getConnection(
          "jdbc:mysql://localhost:3306/training", "root", "root");
      Statement stmt = null;
      try {
        stmt = conn.createStatement();
        int numInserted = 0;
        String sql = "INSERT INTO users (name, gender, age) VALUES ('Adam', 'M', 25)";
        try {
          numInserted += stmt.executeUpdate(sql);
        } catch (SQLException e) {
          System.err.println("Could not update");
          e.printStackTrace();
        }

        sql = "INSERT INTO users (name, gender, age) VALUES ('Eve', 'F', 23)";
        try {
          numInserted += stmt.executeUpdate(sql);
        } catch (SQLException e) {
          System.err.println("Could not update");
          e.printStackTrace();
        }
        System.out.println("Number of rows inserted = " + numInserted);
      } catch (SQLException e) {
        System.err.println("Could not create statement object");
        e.printStackTrace();
      } finally {
        if (stmt != null) {
          stmt.close();
        }
      }
    } catch (SQLException e) {
      System.err.println("Could not open connection!");
      e.printStackTrace();
      System.exit(1);
    } finally {
      if (conn != null) {
        try {
          conn.close();
        } catch (SQLException e) {
          System.err.println("Could not close connection");
          e.printStackTrace();
          System.exit(1);
        }
      }
    }
  }
}