gpt4 book ai didi

java - PreparedStatement 中的这些值/参数是什么意思?

转载 作者:太空宇宙 更新时间:2023-11-04 11:59:22 41 4
gpt4 key购买 nike

我正在学习如何使用 JDBC 创建数据层 DAO tutorial 。然而我在这一点上陷入了困境: PreparedStatement statements = prepareStatement(connection, SQL_UPDATE, false, value); 为什么要这样使用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);
}
}

最佳答案

这个方法在教程中给出,它是 DAOUtil class 的一部分:

public static PreparedStatement prepareStatement
(Connection connection, String sql, boolean returnGeneratedKeys, Object... values)
throws SQLException
{
PreparedStatement statement = connection.prepareStatement(sql,
returnGeneratedKeys ? Statement.RETURN_GENERATED_KEYS : Statement.NO_GENERATED_KEYS);
setValues(statement, values);
return statement;
}

DaoUtilprepareStatement 方法由 DaoImpl 在 try-with-resources 构造中使用。初始化的工作方式不允许使用多个语句,每个资源都必须使用一个表达式进行初始化。该方法将相关的初始化代码组合在一起,以便资源初始化代码可以调用它。

这样,PreparedStatement 的参数就以更具声明性的方式给出,而设置它们的代码则隐藏在实用程序方法中。参数设置非常宽松且容易出错(没有类型检查等问题),所显示的内容对于简洁的教程来说很有用,但不是在实际项目中复制的最佳内容。

如果参数设置代码抛出 SQLException,则方法调用不会返回PreparedStatement,也不会关闭。实际上这通常并不可怕,因为它会发生仅当参数与 sql 中的占位符匹配时出现错误(意味着您遇到更严重的问题)。

重要的是连接和准备好的语句要关闭。否则,您可以尝试不同的编写方式并比较生成的代码。

关于java - PreparedStatement 中的这些值/参数是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41071587/

41 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com