如果SQL语句无法提交,如何记录查询字符串?

时间:2017-08-01 10:14:54

标签: java

有时因任何原因语句无法正确提交DB。例如,如果连接已关闭,则statement.execute()将失败。 有谁知道如何记录语句,以便识别和记录哪些查询字符串未能成功提交?

1 个答案:

答案 0 :(得分:1)

一种解决方案可以是IBM使用LoggableStatement类:

文件地址: https://www.ibm.com/developerworks/library/j-loggable/index.html

Connection connection = DriverManager.getConnection(url,dbUserName,dbPassword);

StringBuffer stringBuffer = new StringBuffer("SELECT * FROM TABLEx");
LoggableStatement statement = new LoggableStatement(connection,stringBuffer.toString());

try {
    statement.execute();
} catch (Exception ex) {
    // write QueryString to a file!
    BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("fileName", true), "cp1256"));
    out.write(statement.getQueryString());
    out.close();
} finally {
    if (statement != null && !statement.isClosed()) {
        statement.close();
    }
}