1. 程式人生 > >jdbc呼叫mysql儲存過程,並獲得結果集合

jdbc呼叫mysql儲存過程,並獲得結果集合

最近碰到一個需要Java呼叫mysql儲存過程並獲得儲存過程結果集的場景.

儲存過程:spilte_result:分割字串儲存到臨時表,並返回臨時表的結果

資料庫執行結果


sum_interface_traffic_result:統計策略流量


現在使用JdbcTemplate進行呼叫儲存過程並且獲得結果

package com.cqs.demo.jdbc;

import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.CallableStatementCallback;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.simple.SimpleJdbcCall;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.sql.CallableStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Component
public class JdbcTemplateProcessCall {
    @Resource
    JdbcTemplate jdbcTemplate;

    public List<SumStrategyTraffic> callProcessResultSet() {
        List result = (List) jdbcTemplate.execute(
                con -> {
                    String storedProc = "{call sum_interface_traffic_result()}";//SQL
                    CallableStatement cs = con.prepareCall(storedProc);
                    return cs;
                }, (CallableStatementCallback) cs -> {
                    List<SumStrategyTraffic> list = new ArrayList<>();
                    boolean exist = cs.execute();
                    if (exist) {
                        ResultSet resultSet = cs.getResultSet();
                        //遍歷結果集
                        while (resultSet.next()) {
//                            System.out.println("strategyId:" + resultSet.getInt(1) + "\tsum_in_traffic:" + resultSet.getFloat(2) + "\tsum_out_traffic:" + resultSet.getFloat(3));
                            SumStrategyTraffic sumStrategyTraffic = new SumStrategyTraffic();
                            sumStrategyTraffic.setStrategyId(resultSet.getInt(1));
                            sumStrategyTraffic.setSumInTraffic(resultSet.getFloat(2));
                            sumStrategyTraffic.setSumOutTraffic(resultSet.getFloat(3));
                            list.add(sumStrategyTraffic);
                        }
                    }
                    return list;
                });
        System.out.println("獲得儲存結果集:");
        result.forEach(System.out::println);
        return result;
    }

    //帶有輸入值的例子
    public void callProcessResultSetWithInput() {
        List result = (List) jdbcTemplate.execute(
                con -> {
                    String storedProc = "{call split_result(?)}";// 呼叫的sql
                    CallableStatement cs = con.prepareCall(storedProc);
                    cs.setString(1, "783,268");// 設定輸入引數的值
                    //cs.registerOutParameter(2, JDBCType.REF_CURSOR);// 註冊輸出引數的型別
                    return cs;
                }, (CallableStatementCallback) cs -> {
                    List<String> list = new ArrayList<>();
                    boolean exist = cs.execute();
                    ResultSet resultSet = cs.getResultSet();
                    if (exist) {
                        while (resultSet.next()) {
//                            System.out.println(resultSet.getString(1));
                            list.add(resultSet.getString(1));
                        }
                    }
                    return list;
                });
        System.out.println("儲存過程結果:"+result);
    }


    //通過SimpleJdbcCall呼叫儲存過程
    public List<SumStrategyTraffic> callProcessResultSetWithSimpleJdbcCall(){
        SimpleJdbcCall call = new SimpleJdbcCall(this.jdbcTemplate)
                .withProcedureName("sum_interface_traffic_result")
                .withoutProcedureColumnMetaDataAccess()
                .returningResultSet("sumStrategyTraffic", BeanPropertyRowMapper.newInstance(SumStrategyTraffic.class));
        Map<String, Object> map = call.execute();
        @SuppressWarnings("unchecked")
        List<SumStrategyTraffic> result = (List<SumStrategyTraffic>) map.get("sumStrategyTraffic");
        System.out.println("儲存過程結果:");
        result.forEach(System.out::println);
        return result;
    }
}

package com.cqs.demo.jdbc;

public class SumStrategyTraffic {
    private int strategyId;
    private float sumInTraffic;
    private float sumOutTraffic;

    public int getStrategyId() {
        return strategyId;
    }

    public void setStrategyId(int strategyId) {
        this.strategyId = strategyId;
    }

    public float getSumInTraffic() {
        return sumInTraffic;
    }

    public void setSumInTraffic(float sumInTraffic) {
        this.sumInTraffic = sumInTraffic;
    }

    public float getSumOutTraffic() {
        return sumOutTraffic;
    }

    public void setSumOutTraffic(float sumOutTraffic) {
        this.sumOutTraffic = sumOutTraffic;
    }

    @Override
    public String toString() {
        return "SumStrategyTraffic{" +
                "strategyId=" + strategyId +
                ", sumInTraffic=" + sumInTraffic +
                ", sumOutTraffic=" + sumOutTraffic +
                '}';
    }

}
JUnit單元測試
package com.cqs.demo.jdbc;

import com.cqs.demo.base.BaseConfigurationTest;
import org.junit.Test;

import javax.annotation.Resource;

/**
 * Created by cqs on 16-12-4.
 */
public class JdbcTemplateProcessCallTest extends BaseConfigurationTest {

    @Resource
    JdbcTemplateProcessCall jdbcTemplateProcessCall;

    @Test
    public void callProcessResultSet() throws Exception {
        jdbcTemplateProcessCall.callProcessResultSet();
    }

    @Test
    public void callProcessResultSetWithInput() throws Exception {
        jdbcTemplateProcessCall.callProcessResultSetWithInput();
    }

    @Test
    public void callProcessResultSetWithSimpleJdbcCall() throws Exception {
        jdbcTemplateProcessCall.callProcessResultSetWithSimpleJdbcCall();
    }

}

執行結果