Java ResultSet, SetObject vs SetString/SetDate/etc

前端 未结 2 1855
没有蜡笔的小新
没有蜡笔的小新 2020-12-25 13:37

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

2条回答
  •  清歌不尽
    2020-12-25 14:10

    You can do so.

    E.g.

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

    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.

提交回复
热议问题