1

I'm using a CallableStatement to execute a SQL query with named parameters, and I'm getting different results depending on the order in which I bind the parameters. Here's my full test:

public void test() throws SQLException {
    OracleDataSource ds = new OracleDataSource();
    ds.setUser("abcd");
    ds.setPassword("a");
    ds.setURL("jdbc:oracle:thin:@efgh:1521:orcl");
    Connection connection = ds.getConnection();
    CallableStatement stmt = connection.prepareCall("select :a col_a, :b col_b from dual");
    stmt.setObject(":b", "b");
    stmt.setObject(":a", "a");
    ResultSet resultSet = stmt.executeQuery();
    resultSet.next();

    Assert.assertEquals("a", resultSet.getObject("col_a"));
    Assert.assertEquals("b", resultSet.getObject("col_b"));

}

It fails because col_a contains "b", and col_b contains "a". If I switch the two calls to stmt.setObject to make them in the order the variables appear in the query, then it works.

I've also tried:

  • using setString/getString instead of setObject/getObject
  • referencing columns by their index (resultSet.getObject(1) for col_a and 2 for col_b)
  • combining both: resultSet.getString(resultSet.findColumn("col_a"))

Any idea of what I'm doing wrong, or of any other way I could be doing this? I can't do with positioned parameters (with ?) in PreparedStatement, as I can get different queries with the same parameters in different order.

For instance, I could get those two queries to execute:

  • select nvl(foo, :a), :b || something from my_table
  • select decode(:b, 'b', aaa, ccc), eee || :a from another_table

The statements have nothing in common except the presence of the variables :a and :b. But they are not in the same order, which means I cannot replace them with ? and then use a PreparedStatement with variables binding with stmt.setObject(1, a); stmt.setObject(2, b);, because it would work for the first one, but not for the second.

In case it's useful, I'm using ojdbc6-11.2.0.2.0, and the database is also in 11.2.0.2.0.

4

0 回答 0