Java ResultSet,SetObject与SetString / SetDate / etc [英] Java ResultSet, SetObject vs SetString/SetDate/etc
问题描述
我想知道在准备语句时是否有人认为所有数据类型都使用 PreparedStatement.setObject
作为不好的做法。一个用例就是一个带有通用executeQuery()方法的DAO,它可以重用于所有查询,而不必担心它的数据类型。
I'd like to know whether anyone considers using PreparedStatement.setObject
for all data types as bad practice when preparing a statement. A use case for this would be a DAO with a generic executeQuery() method which can be re-used for all queries without having to worry about its data types.
推荐答案
你可以这样做。
例如
preparedStatement = connection.prepareStatement(SQL_INSERT);
SqlUtil.setValues(preparedStatement, user.getName(), user.getPassword(), user.getAge());
with
public static void setValues(PreparedStatement preparedStatement, Object... values) throws SQLException {
for (int i = 0; i < values.length; i++) {
preparedStatement.setObject(i + 1, values[i]);
}
}
JDBC驱动程序将进行类型检查。唯一的缺点可能是(次要)开销,但与最终可用的更好的可维护代码相比,这可以忽略不计。此外,大多数ORM框架(如Hibernate / JPA)也深入使用。
The JDBC driver will do the type checking. The only disadvantage is maybe the (minor) overhead, but this is negligible as compared to the better maintainable code you end up with. Also, most ORM frameworks like Hibernate/JPA also uses that deep under the covers.
这篇关于Java ResultSet,SetObject与SetString / SetDate / etc的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!