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);
System.setErr(stderr);
String query = "SELECT Name,Description,Qty,Cost,Sell_Price FROM Stock";
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
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) {
e.printStackTrace(errLog);
} 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());
e.printStackTrace(errLog);
System.err.println();
}
stderr.close();
}
}
Related examples in the same category