Get result sql from Prepared Statement by Oracle

非 Y 不嫁゛ 提交于 2020-01-24 13:00:09

问题


I'm looking for posibility to get result sql (with injected parameter) from prepared statement in java for Oracle implementation.

By MySQL the method toString() get wanted sql over the method asSql() from com.mysql.jdbc.PreparedStatement.

But by Oracle implementation oracle.jdbc.driver.OraclePreparedStatementWrapper, I can't find the way to get a result sql.


回答1:


I believe there's no such thing with the OraclePreparedStatement.

If you absolutely need that feature, you could wrap some code around the PreparedStatement I guess:

public class LoggingPreparedStatement implements PreparedStatement {

    private PreparedStatement delegate;

    private String sql;

    private Map<Integer,Object> parameter = new TreeMap<Integer,Object>();

    public LoggingPreparedStatement(Connection con, String sql) throws SQLException {
        this.sql = sql;
        this.delegate = con.prepareStatement(sql);      
    }

    @Override
    public void setString(int parameterIndex, String x) throws SQLException {
        parameter.put(parameterIndex, x);
        delegate.setString(parameterIndex, x);
    }

    //What you asked for
    public String getSQL() {
        String returnSQL = sql;
        //TreeMap returns sorted by key
        for(Object o : parameter.values()) {
            //Replace first ? with the value
            returnSQL = returnSQL.replaceFirst("\\?", o.toString());
        }
        return returnSQL;
    }

    //Lots of other methods to implement and delegate to original statement
    [...]
}

You would then instead of

PreparedStatement ps = con.prepareStatement(sql);

Need to change to

LoggingPreparedStatement ps = new LoggingPreparedStatement(con, sql);

So overall the process is quite painful.



来源:https://stackoverflow.com/questions/34412289/get-result-sql-from-prepared-statement-by-oracle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!