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?
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.
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.
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 ...
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With