You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PostgreSQL存储过程结果显示及Spring Boot JDBC调用问题

PostgreSQL存储过程问题解决方案

一、pgAdmin中显示存储过程查询结果

首先修正你存储过程里的参数名冲突问题(原代码中brand_name = brand_name会将参数与自身比较,导致永远返回全表数据),修改后的存储过程:

CREATE OR REPLACE PROCEDURE get_mobiles(p_brand_name varchar)
LANGUAGE SQL
AS $$
SELECT * FROM mobile_phone where brand_name = p_brand_name;
$$;

在pgAdmin中查看结果的操作步骤:

  • 打开pgAdmin的查询工具,执行调用语句:
    CALL get_mobiles('指定品牌名'); -- 替换为实际要查询的品牌
    
  • 执行完成后,切换到查询工具的数据输出标签页,即可看到存储过程返回的结果集。如果未显示,确认存储过程的SELECT语句确实能查询到数据,或检查是否切换到了正确的标签页。

二、Spring Boot JDBC Template调用存储过程并获取结果

使用CallableStatement配合JDBC Template来执行存储过程,示例代码如下:

1. 注入JdbcTemplate

@Autowired
private JdbcTemplate jdbcTemplate;

2. 编写调用方法(实体类映射版)

假设存在实体类MobilePhone对应mobile_phone表的字段,编写查询方法:

public List<MobilePhone> getMobilesByBrand(String brandName) {
    String callSql = "{CALL get_mobiles(?)}";
    
    return jdbcTemplate.execute(
        // 创建CallableStatement并设置参数
        con -> {
            CallableStatement cs = con.prepareCall(callSql);
            cs.setString(1, brandName);
            return cs;
        },
        // 处理结果集并映射为实体类
        cs -> {
            List<MobilePhone> mobiles = new ArrayList<>();
            ResultSet rs = cs.executeQuery();
            
            while (rs.next()) {
                MobilePhone phone = new MobilePhone();
                phone.setId(rs.getInt("id"));
                phone.setBrandName(rs.getString("brand_name"));
                phone.setModel(rs.getString("model"));
                // 根据表结构补充其他字段映射
                mobiles.add(phone);
            }
            
            rs.close();
            return mobiles;
        }
    );
}

3. 编写调用方法(Map列表版,无需实体类)

如果不需要实体类,直接返回键值对形式的结果:

public List<Map<String, Object>> getMobilesByBrand(String brandName) {
    String callSql = "{CALL get_mobiles(?)}";
    
    return jdbcTemplate.execute(
        con -> {
            CallableStatement cs = con.prepareCall(callSql);
            cs.setString(1, brandName);
            return cs;
        },
        cs -> {
            List<Map<String, Object>> resultList = new ArrayList<>();
            ResultSet rs = cs.executeQuery();
            ResultSetMetaData metaData = rs.getMetaData();
            int columnCount = metaData.getColumnCount();
            
            while (rs.next()) {
                Map<String, Object> row = new HashMap<>();
                for (int i = 1; i <= columnCount; i++) {
                    row.put(metaData.getColumnName(i), rs.getObject(i));
                }
                resultList.add(row);
            }
            
            rs.close();
            return resultList;
        }
    );
}

内容的提问来源于stack exchange,提问作者Shyam Kumar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 19:23:15