PreparedStatement,在插入一组数据时,哪个方法能自动判断插入的数据类型和数据库中的匹配呢?谢谢
比如插入字符串是setString(i, Sql);
语句是insert into (表名)(a,b,c)values(?,?,?)
我想说的是,“?”在使用setString()方法时,如果传入的值多,想做一个for循环自动插进去,插的过程中自己判断数据类型。谢谢
用setObject, 可以参考spring源代码StatementCreatorUtils
if (isStringValue(inValue.getClass())) {
ps.setString(paramIndex, inValue.toString());
}
else if (isDateValue(inValue.getClass())) {
ps.setTimestamp(paramIndex, new java.sql.Timestamp(((java.util.Date) inValue).getTime()));
}
else if (inValue instanceof Calendar) {
Calendar cal = (Calendar) inValue;
ps.setTimestamp(paramIndex, new java.sql.Timestamp(cal.getTime().getTime()), cal);
}
else {
// Fall back to generic setObject call without SQL type specified.
ps.setObject(paramIndex, inValue);
}
/**
* Check whether the given value can be treated as a String value.
*/
private static boolean isStringValue(Class<?> inValueType) {
// Consider any CharSequence (including StringBuffer and StringBuilder) as a String.
return (CharSequence.class.isAssignableFrom(inValueType) ||
StringWriter.class.isAssignableFrom(inValueType));
}
/**
* Check whether the given value is a {@code java.util.Date}
* (but not one of the JDBC-specific subclasses).
*/
private static boolean isDateValue(Class<?> inValueType) {
return (java.util.Date.class.isAssignableFrom(inValueType) &&
!(java.sql.Date.class.isAssignableFrom(inValueType) ||
java.sql.Time.class.isAssignableFrom(inValueType) ||
java.sql.Timestamp.class.isAssignableFrom(inValueType)));
}