【发布时间】:2017-04-25 14:11:42
【问题描述】:
我正在学习如何通过DAO tutorial 使用 JDBC 创建数据层。
但是我在这一点上卡住了:PreparedStatement statement = prepareStatement(connection, SQL_UPDATE, false, values); 为什么要以这种方式使用 prepareStatement?
如有任何解释和建议,我将不胜感激。
我查看了documentation 并搜索了相关示例,但没有找到对这种结构的任何解释。我熟悉这样的表达式,当 connection 对象调用 prepareStatement 方法时:
Connection connection = daoFactory.getConnection();
PreparedStatement statement = connection.prepareStatement(SQL);
但我不明白为什么 PreparedStatement 的实现方式如下例所示:
public void update(User user) throws DAOException {
if (user.getId() == null) {
throw new IllegalArgumentException("User is not created yet, the user ID is null.");
}
Object[] values = {
user.getEmail(),
user.getFirstname(),
user.getLastname(),
toSqlDate(user.getBirthdate()),
user.getId()
};
try (
Connection connection = daoFactory.getConnection();
PreparedStatement statement = prepareStatement(connection, SQL_UPDATE, false, values);
) {
int affectedRows = statement.executeUpdate();
if (affectedRows == 0) {
throw new DAOException("Updating user failed, no rows affected.");
}
} catch (SQLException e) {
throw new DAOException(e);
}
}
【问题讨论】:
-
prepareStatement是用户定义的方法吗?请发布该方法的代码。 -
@JitinKodian 我还认为它可能是一些用户定义的方法。但在BalusC tutorial : 中没有找到它
标签: java database jdbc prepared-statement dao