基本的に、Java プログラムから生成されたエラーのログを作成し、それらを 2 つの列 (エラーと日付) で SQL テーブルに保存しようとしています。
Try and catch はエラーをメソッドに送信します。メソッドはデータベースに挿入されるはずですが、どこかで失敗します。私はJavaに十分慣れていないので、適切にデバッグする方法や、問題が発生している場所の詳細を取得する方法がわからない
方法はこちら。
public void createErrorLog(Exception error) throws SQLException{
// Error as String
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
error.printStackTrace(pw);
sw.toString(); // stack trace as a string
String errorOne = sw.toString();
System.out.println(errorOne);
// Date
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
Date date = new Date();
String dateString = dateFormat.format(date);
Connection conn = null;
try {
conn = DriverManager.getConnection(CONN_STRING, USERNAME, PASSWORD);
System.out.println("Connected to database.");
String insertSaleProperty = "INSERT INTO ErrorLogs"
+ "(Error, "
+ "Time, "
+ "(?,?)";
PreparedStatement preparedStatement = conn.prepareStatement(insertSaleProperty);
preparedStatement.setString(1, errorOne);
preparedStatement.setString(2, dateString);
// execute insert SQL statement
preparedStatement.executeUpdate();
} catch (SQLException e) {
System.err.println("Cannot write to database.");
} finally {
if(conn != null){
conn.close();
}
}
}