views:

74

answers:

2

Hi,

I have a stored procedure get_data(estargs set(char(1000) not null)) in the informix 11.5 database. I have to use this stored procedure in order to get a value from the database.

I tried using this way but it fails:

conn = dataSource.getConnection();
            String [] arrayObj={"and code = 'Value1'","and lmt= 10000.000"};
            CallableStatement test=conn.prepareCall("{call get_data(?)}");
            test.setObject(1, arrayObj);
            test.execute();
            ResultSet testrs = test.getResultSet();
            while (testrs.next()) {
                int data = testrs.getInt(1);
                System.out.println(data);

            }

This is not working. What do you think I am doing wrong?

A: 

Have you tried using java.sql.Array?

Georgy Bolyuba
I saw it but I dont know how to convert Java Array to java.sql.Array.
Sameer Malhotra
Not needed. This ain't going to work.
BalusC
A: 

That's not possible. Replace

conn.prepareCall("{call get_data(?)}");

by

conn.prepareCall("{call get_data(?, ?)}");

and replace

test.setObject(1, arrayObj);

by

test.setObject(1, arrayObj[0]);
test.setObject(2, arrayObj[1]);

Related question:


Update: make it all more "dynamically", you'd like to generate and populate the placeholders yourself with help of the following two utility methods:

public static String preparePlaceHolders(int length) {
    StringBuilder builder = new StringBuilder(length * 2 - 1);
    for (int i = 0; i < length; i++) {
        if (i > 0) builder.append(',');
        builder.append('?');
    }
    return builder.toString();
}

public static void setValues(PreparedStatement preparedStatement, Object... values) throws SQLException {
    for (int i = 0; i < values.length; i++) {
        preparedStatement.setObject(i + 1, values[i]);
    }
}

which can be used as follows:

private static final String SQL_CALL_GET_DATA = "{call get_data(%s)}";

// ...
String sql = String.format(SQL_CALL_GET_DATA, preparePlaceholders(arrayObj.length));
statement = connection.prepareCall(sql);
setValues(statement, arrayObj);
// ...
BalusC
I cannot do that because I would know only at run time how many arguments I am passing in the stored procedure.
Sameer Malhotra
Did you follow the "Related question" link? It contains an example how to generate `?,?,?` etc and populate it dynamically.
BalusC