开发者

How to pass an array object from jdbc code

I have a stored procedure g开发者_StackOverflow社区et_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?


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:

  • How to set multiple values in IN clause?

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);
// ...


Have you tried using java.sql.Array?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜