本文介绍了从Oracle的Prepared Statement获取结果sql的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找从Java中准备好的语句中获取结果sql(具有注入参数)的可能性,以用于Oracle实现.

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

通过MySQL,方法toString()通过com.mysql.jdbc.PreparedStatement的方法asSql()获得了所需的sql.

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

但是通过Oracle实现oracle.jdbc.driver.OraclePreparedStatementWrapper,我找不到获取结果sql的方法.

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

推荐答案

我相信OraclePreparedStatement没有这样的东西.

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

如果您绝对需要该功能,则可以在我想的PreparedStatement周围包装一些代码:

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
    [...]
}

然后您将代替

PreparedStatement ps = con.prepareStatement(sql);

需要更改为

LoggingPreparedStatement ps = new LoggingPreparedStatement(con, sql);

因此,整个过程非常痛苦.

So overall the process is quite painful.

这篇关于从Oracle的Prepared Statement获取结果sql的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-26 11:41