PreparedStatement setString(...)for all,即使cororesponding数据类型是一个整数 [英] PreparedStatement setString(...) for all, even if corrsponding data type is an integer

查看:68
本文介绍了PreparedStatement setString(...)for all,即使cororesponding数据类型是一个整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到过以下代码,我觉得它做错了:

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

(请注意,这是JDK 1.4.2,因此列表未输入)

(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());

这就是我所关注的:

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?

推荐答案

考虑使用PreparedStatement setObject()方法 setString()

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

PreparedStatement setObject()会尝试为您转换任何 java.lang 类型在编译时是未知的。

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

所以使用更新的for循环(假设你有java 5.0)和泛型空值处理:

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);
    }
}

请注意 setNull()可以接受键入作为第二个参数(如果已知)。

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

这篇关于PreparedStatement setString(...)for all,即使cororesponding数据类型是一个整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆