Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PreparedStatement setString(...) for all, even if corrsponding data type is an integer

I have come across the following codes i feel it is doing the wrong thing:

(Note that this is JDK 1.4.2, therefore the list is not typed)

StringBuffer queryBuffer = new StringBuffer();
ArrayList temp = new ArrayList();

... 
queryBuffer.append("and sb.POSTCODE = ? ");
temp.add(postcode);
...

conn = ConnectionManager.getConnection();       
pstmt = conn.prepareStatement(queryBuffer.toString());

This is what i am concerned about:

for(int i=0; i<temp.size(); i++) {
    log.debug("setString("+ (i+1) + "," + (String)temp.get(i) + ")");
    pstmt.setString(i+1, (String)temp.get(i));
}

But i have noted that some of the corresponding data types (field) in the database are integer, and dates, would this be alright?

like image 539
Oh Chin Boon Avatar asked May 16 '12 01:05

Oh Chin Boon


People also ask

What does PreparedStatement setString do?

executeQuery(); Methods of PreparedStatement: setInt(int, int): This method can be used to set integer value at the given parameter index. setString(int, string): This method can be used to set string value at the given parameter index.

Which are the parameters setString () method?

setString. Sets the designated parameter to the given Java String value. The driver converts this to an SQL VARCHAR or LONGVARCHAR value (depending on the argument's size relative to the driver's limits on VARCHAR values) when it sends it to the database.

What method on a PreparedStatement can you use to execute a select query?

As with Statement objects, to execute a PreparedStatement object, call an execute statement: executeQuery if the query returns only one ResultSet (such as a SELECT SQL statement), executeUpdate if the query does not return a ResultSet (such as an UPDATE SQL statement), or execute if the query might return more than one ...

What is the use of PreparedStatement in JDBC?

The PreparedStatement interface extends the Statement interface it represents a precompiled SQL statement which can be executed multiple times. This accepts parameterized SQL quires and you can pass 0 or more parameters to this query.


1 Answers

Consider using the PreparedStatement setObject() method instead of setString().

The PreparedStatement setObject() will attempt to convert any of the java.lang types for you if the type is unknown at compile time.

so with an updated for loop (assuming you have java 5.0) and generic null handling:

int i = 0;
for(Object value : temp) {
    if (value == null) {
        // set null parameter if value type is null and type is unknown
        pstmt.setNull(++i, Integer.MIN_VALUE); 
    } else {
        pstmt.setObject(++i, value);
    }
}

Note that setNull() can accept a type as the 2nd parameter if it is known.

like image 94
pd40 Avatar answered Sep 18 '22 15:09

pd40