【问题标题】:How to create connection object for PreparedStatement in SpringBoot如何在 Spring Boot 中为 PreparedStatement 创建连接对象
【发布时间】:2021-06-25 11:51:54
【问题描述】:
            try (Connection connection = DriverManager
            .getConnection("jdbc:mysql://localhost:3306/mysql_database?useSSL=false", "root", "root");

            // Step 2:Create a statement using connection object
            PreparedStatement preparedStatement = connection.prepareStatement(UPDATE_USERS_SQL)) {
            preparedStatement.setString(1, "Ram");
            preparedStatement.setInt(2, 1);

            // Step 3: Execute the query or update query
            preparedStatement.executeUpdate();

为每个查询创建连接对象并关闭它很昂贵,有没有其他方法可以在 spring boot 中使用准备好的语句,其次如何创建连接对象,我在 application.yml 文件中有数据库信息

【问题讨论】:

标签: spring-boot


【解决方案1】:

为每个查询创建连接对象并关闭它是昂贵的

这正是使用连接池的原因,例如 c3p0、dbcp 或更现代的 Hikari 连接池,它们与 Spring Boot 2 生态系统完美集成。要访问数据,您可能需要在原始 JDBC API 上使用瘦包装器,这相当麻烦。 Spring 提供了一个像这样的包装器,称为 JdbcTemplate(它比 hibernate 更“先进”,它不执行任何自动映射,不生成疯狂和不那么疯狂的查询),它的行为非常像jdbc 但可以让您免于创建准备好的语句、迭代结果集等。

我不会在这里真正解释如何使用 JdbcTemplate,我只会说明您可能会从中获得连接,但我认为您永远不需要它。 当然,在底层它会与 Hikari 连接池集成,因此实际连接将从池中获取。

Here你可以找到这样一个具有完整 DAO 实现(称为存储库)和 JdbcTemplate 对象配置的工具的示例

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-19
    • 1970-01-01
    • 2016-12-24
    相关资源
    最近更新 更多