我有一个编辑成员的方法,我想将错误打印到文件中,但是如果我尝试将堆栈跟踪打印到Error_Report.txt文件中,我一直无法取消引用错误。无论如何我可以把它打印出来吗? 这是我的代码。
public void edit() {
FileWriter fw = new FileWriter(new File("Error_Report.txt"));
Connection con;
Statement stmt;
ResultSet rs;
int id = (int)_id.getSelectedItem();
String name = _name.getText();
String user = _username.getText();
String pass = _password.getText();
String pos = _position.getSelectedItem().toString();
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:collegesys",
"root", "0blivi0n");
stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_READ_ONLY);
PreparedStatement prep = con.prepareStatement("UPDATE `main` WHERE ID = ?");
prep.setInt(1, id);
prep.setString(2, name);
prep.setString(3, user);
prep.setString(4, pass);
prep.setString(5, pos);
prep.execute();
} catch(SQLException sqle) {
String sql = sqle.printStackTrace().toString();
fw.write("" + sql);
} catch(ClassNotFoundException cnfe) {
fw.write("" + cnfe);
}
}
答案 0 :(得分:5)
您的问题是printStackTrace
没有返回任何内容,因此无法转换为字符串。写这样的。
PrintWriter writer = new PrintWriter(fw);
sqle.printStackTrace(writer);
writer.close();
答案 1 :(得分:4)
sqle.printStackTrace()
返回void,不能用作参数。将您的代码更改为以下内容:
catch(SQLException sqle) {
StringBuilder sb = new StringBuilder();
StackTraceElement[] st = sqle.getStackTrace();
for(StackTraceElement s : st) {
sb.append(s);
sb.append('\n');
}
fw.write(sb.toString());
}