1. 添加 PostgreSQL 依赖

pom.xml 文件中添加以下依赖:

<dependency>
    <groupId>org.postgresql</groupId>
    <artifactId>postgresql</artifactId>
    <version>42.2.23</version>
</dependency>
  1. 配置数据库连接

application.properties 文件中添加以下配置:

spring.datasource.url=jdbc:postgresql://localhost:5432/dbname
spring.datasource.username=username
spring.datasource.password=password
spring.datasource.driver-class-name=org.postgresql.Driver

其中,dbname 为数据库名称,username 为数据库用户名,password 为数据库密码。

  1. 编写查询代码

在 Spring Boot 中,可以使用 JdbcTemplate 来执行 SQL 查询。在代码中注入 JdbcTemplate,然后使用 JdbcTemplatequery 方法执行查询。

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

@Service
public class UserService {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    public List<User> getUsers() {
        String sql = 'SELECT * FROM users';
        List<User> users = jdbcTemplate.query(sql, (rs, rowNum) -> {
            User user = new User();
            user.setId(rs.getInt('id'));
            user.setName(rs.getString('name'));
            user.setEmail(rs.getString('email'));
            return user;
        });
        return users;
    }
}

在上面的代码中,使用 JdbcTemplatequery 方法执行查询,将查询结果映射为 User 对象。可以使用 Lambda 表达式来简化代码。

  1. 测试查询结果

Controller 中调用 UserServicegetUsers 方法,将查询结果返回给前端。

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping('/users')
    public List<User> getUsers() {
        List<User> users = userService.getUsers();
        return users;
    }
}

启动应用程序,并访问 http://localhost:8080/users,即可看到查询结果。

SpringBoot 连接 PostgreSQL 数据库并执行 SQL 查询

原文地址: https://www.cveoy.top/t/topic/jpRg 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录