I'm using JDBC with Oracle 8i and I have the following prepared
statement code:
...
String sql = "Select ID from Users where level in (?)";
PreparedStatement statement = connection.prepareStatement(sql);
String levels = "1, 2, 3";
statement.setString(1, levels);
rs = (ResultSet) statement.executeQuery();
...
- The executeQuery call fails with: "ORA-01722: invalid number".
- Level is an integer field in the users table
So, I'm guessing I've got to do something different here to handle
these kinds of "list" parameters. Any thoughts?
Daniel Dittmar - 06 Oct 2004 16:16 GMT
> String sql = "Select ID from Users where level in (?)";
>
[quoted text clipped - 3 lines]
>
> statement.setString(1, levels);
- keep one PreparedStatement around for every possible number of
elements in the parameter list => in (?), in (?, ?). You could create a
class that creates (and caches) the PreparedStatements on the fly
- create a PreparedStatement with many parameters and fill unused
parameters with setNull ()
- try batch execution. I know of at least one database where sending
multiple parameter sets for a SELECT results in the UNION. But this
would work only for 'level in (?)', not for 'level not in (?)'.
Daniel
Chuck Simpson - 31 Oct 2004 20:48 GMT
> I'm using JDBC with Oracle 8i and I have the following prepared statement
> code:
[quoted text clipped - 18 lines]
> So, I'm guessing I've got to do something different here to handle these
> kinds of "list" parameters. Any thoughts?
Probably the easiest solution in Java is to create a statement
String in a StringBuffer and append the same number of placeholders
(?) as list elements, convert to a String, create a PreparedStatement
and fill in the placeholders. Eg:
StringBuffer sb = new StringBuffer(
"Select ID from Users where level in (?");
int n = list.size();
for(int i = 1; i < n; i++) {
sb.append(",?");
}
PreparedStatement ps = con.prepareStatement(sb.toString());
for(int i = 0; i < n; i++) {
ps.setObject(i, list.get(i));
}
ResultSet rs = ps.executeQuery();
Hope this helps.
Chuck
Chuck Simpson - 31 Oct 2004 20:56 GMT
>> I'm using JDBC with Oracle 8i and I have the following prepared
>> statement code:
[quoted text clipped - 39 lines]
>
> Chuck
PS: I should have put the line:
sb.append(")");
just before creating the PreparedStatement to close the in operand.
Chuck