我正在尝试连接到数据库,运行查询并打印出查询。到目前为止,我已经完成了工作,但是我需要获取输出并将其中的特定部分分配给String
String
public static void main(String args[]) { BasicConfigurator.configure(); Logger.getGlobal().setLevel(Level.INFO); PreparedStatement preparedStatement = null; try { connect(); String sql = "SELECT * FROM foo WHERE ID = ?"; preparedStatement = connection.prepareStatement(sql); preparedStatement.setInt(1, 1); try (ResultSet resultSet = preparedStatement.executeQuery()) { while (resultSet.next()) { break; } } //String usedSql = "query should go here"; } catch (SQLException ex) { Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex); } finally { if (preparedStatement != null) { try { preparedStatement.close(); } catch (SQLException ex) { Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex); } } disconnect(); } }
我正在使用log4jdbc监视我的查询。
此刻,我得到如下记录的输出:
594 [main] DEBUG jdbc.foo - 1. Connection.new Connection returned java.sql.DriverManager.getConnection(DriverManager.java:664) 608 [main] DEBUG jdbc.foo - 1. PreparedStatement.new PreparedStatement returned com.example.Test.main(Test.java:63) 608 [main] DEBUG jdbc.foo - 1. Connection.prepareStatement(SELECT * FROM foo WHERE ID = ?) returned net.sf.log4jdbc.PreparedStatementSpy@7d70d1b1 com.example.Test.main(Test.java:63) 608 [main] DEBUG jdbc.foo - 1. PreparedStatement.setInt(1, 1) returned com.example.Test.main(Test.java:64) 608 [main] DEBUG jdbc.foo - 1. PreparedStatement.setMaxRows(1) returned com.example.Test.main(Test.java:65) 609 [main] DEBUG jdbc.sqlonly - com.example.Test.main(Test.java:66) 1. SELECT * FROM foo WHERE ID = 1
我想分配SELECT * FROM foo WHERE ID = 1给usedSql。我该怎么做呢?
SELECT * FROM foo WHERE ID = 1
usedSql
通常,a preparedStatement.toString()将为您提供查询(包括绑定参数)。但这取决于的实际实现PreparedStatement(例如,使用PostgreSQL隐式实现)。
preparedStatement.toString()
PreparedStatement
您提到为您带来preparedStatement.toString()回报net.sf.log4jdbc.PreparedStatementSpy@7d70d1b1。我对 log4jdbc 并不熟悉,但是我似乎PreparedStatementSpy正在包装您的实际代码PreparedStatement。要从您的preparedStatement尝试中获取它,例如
net.sf.log4jdbc.PreparedStatementSpy@7d70d1b1
PreparedStatementSpy
preparedStatement
if(preparedStatement instanceof PreparedStatementSpy) usedSql = ((PreparedStatementSpy) preparedStatement).getRealStatement().toString();
编辑 :因为您使用的是 Derby, 所以简单toString()不会做。一种解决方法是使用use PreparedStatementSpy.dumpedSql(),它将返回 log4jdbc 用于记录的相同字符串。不幸的是,它是一种 受保护的 方法,您必须使用反射:
toString()
PreparedStatementSpy.dumpedSql()
if (preparedStatement instanceof PreparedStatementSpy) { Method m = PreparedStatementSpy.class.getDeclaredMethod("dumpedSql"); m.setAccessible(true); usedSql = (String) m.invoke(preparedStatement); } // omitted exception handling