alex
alex

Reputation: 227

How to add parameters in PreparedStatement in Postgresql JDBC without manually setting the types

Is this possible? We're using a PreparedStatementSetter, and the code is littered with statements like preparedStatement.setString(4,"string");

We have a lot of columns, so this is unfortunate. It seems like it ought to be possible via the various metadata JDBC methods, and therefore I assume it has already been done (only half-joking).

We're on Spring 3.0 and PGJDBC 9.1-903

Upvotes: 0

Views: 2344

Answers (1)

Luiggi Mendoza
Luiggi Mendoza

Reputation: 85779

Use PreparedStatement#setObject and let the JDBC driver identify the type of the parameter by itself.

For example, doing

preparedStatement.setObject(4,"string");

Will execute, in the end

preparedStatement.setString(4,"string");

You can even create a method to insert the parameters for you. Here's a basic example:

public void addParameters(PreparedStatement pstmt, Object ... parameters)
    throws SQLException {
    int paramIndex = 1;
    for (Object param : parameters) {
        pstmt.setObject(paramIndex++, param);
    }
}

And just set the parameters by:

PreparedStatement preparedStatement = ...
addParameters(preparedStatement, 1, "string", new java.util.Date());

Upvotes: 2

Related Questions