Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
247 views
in Technique[技术] by (71.8m points)

java - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...