Logging errors to a file : SQLException « Database SQL JDBC « Java

Logging errors to a file

import java.io.FileOutputStream;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.GregorianCalendar;

public class Logging {
  public static void main(String args[]) throws Exception {
    FileOutputStream errors = new FileOutputStream("StdErr.txt", true);
    PrintStream stderr = new PrintStream(errors);
    PrintWriter errLog = new PrintWriter(errors, true);

    String query = "SELECT Name,Description,Qty,Cost,Sell_Price FROM Stock";

    try {
      Connection con = DriverManager.getConnection("jdbc:odbc:Inventory");
      Statement stmt = con.createStatement();
      ResultSet rs = stmt.executeQuery(query);
      while (rs.next()) {
        String name = rs.getString("Name");
        String desc = rs.getString("Description");
        int qty = rs.getInt("Qty");
        float cost = rs.getFloat("Cost");
    } catch (ClassNotFoundException e) {
    } catch (SQLException e) {
      System.err.println((new GregorianCalendar()).getTime());
      System.err.println("Thread: " + Thread.currentThread());
      System.err.println("ErrorCode: " + e.getErrorCode());
      System.err.println("SQLState:  " + e.getSQLState());
      System.err.println("Message:   " + e.getMessage());
      System.err.println("NextException: " + e.getNextException());


Related examples in the same category

1.Get Error Code, SQL State, Message
2.Handling a SQL Exception: how to retrieve the information in a SQLException.
3.Print the stack trace for a SQLException to STDERR.