后端开发 - 使用JDBC调用存储过程

首先

存储过程是什么?

存储过程
存储过程(Stored Procedure)是在大型数据库系统中,一组为了完成特定功能的SQL 语句集,存储在数据库中,经过第一次编译后调用不需要再次编译,用户通过指定存储过程的名字并给出参数(如果该存储过程带有参数)来执行它。存储过程是数据库中的一个重要对象。 --百度百科

使用存储过程有什么作用?

“存储在数据库中,经过第一次编译后调用不需要再次编译”

节省编译的时间,这是其中一点。还有一点,在开发过程中服务的性能瓶颈多是发生在在数据库的I/O操作中,
那么我们把要做的事情通过调用一个存储过程来取代多次与数据库的交互可以大大提高服务的性能。

存储过程的写法这里不介绍了

记录一下使用JDBC来调用存储过程的方法

使用JDBC连接数据库的工具类

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * 原生jdbc工具类,解决分片中间件无法调用存储过程
 * @author hql
 */
@Component
public class JdbcUtil {
    @Value("${jdbc.url}")
    private String url ;
    @Value("${jdbc.username}")
    private String username ;
    @Value("${jdbc.password}")
    private String password ;
    private JdbcUtil(){}
    public Connection getConn() throws SQLException {
        return DriverManager.getConnection(this.url,this.username,this.password);
    }
    public void close(Connection conn){
        if (conn!=null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

application.properties中关于jdbc连接的参数配置

#自定义jdbc连接
jdbc.url=jdbc:mysql://localhost:3306/db_name?useUnicode=true&characterEncoding=utf8&useSSL=true&rewriteBatchedStatements=true
jdbc.username=root
jdbc.password=xxxx

返回单个值

    //注入工具类
    @Autowired
    private JdbcUtil jdbcutil;

    private String getCheckVoucherProcedureQuerySingleResult(
            Long id, String types, Date startTime, Date endTime, 
            String sharding) throws Exception {
        Connection conn = null;
        CallableStatement cs = null;
        String result;
        try {
            //通过工具类,获取数据库链接对象
            conn= jdbcUtil.getConn();
            cs = conn.prepareCall("{call InitForCreateTable(?,?,?,?,?,?)}");
            cs.setLong("unitId",id);
            cs.setDate("endTime", (java.sql.Date) endTime);
            cs.setString("sharding",sharding);
            cs.registerOutParameter("result", Types.VARCHAR);
            cs.execute();
            result = cs.getString("result");
        } catch (Exception e) {
            e.printStackTrace();
            throw  new Exception("调用存储过程异常");
        }
        finally {
            if(cs != null){
                cs.close();
            }
            jdbcUtil.close(conn);
        }
        return result;
    }

返回结果集

    public List<DetailAccountProcedure> getDetailAccountProcedureProcedureQUeriesResultSet(
            String fiscalPeriod, Long unitId, String subjectCode, 
            Date startDate, Date selectDate, Date endDate, 
            String voucherT, Date topOneDate, int isZero) throws Exception {
        Connection con = null;
        CallableStatement cs = null;
        List<DetailAccountProcedure> resultSet = new ArrayList<>();
        try {
            con = jdbcUtil.getConn();
            cs = con.prepareCall("{call DetailAccountProcedure(?,?,?,?,?,?,?,?,?,?)}");
            cs.setLong("unitId", unitId);
            cs.setString("sharding", fiscalPeriod);
            cs.execute();
            ResultSet rs = cs.getResultSet();
            while (rs != null && rs.next()) {
                DetailAccountProcedure result = new DetailAccountProcedure(
                    rs.getLong("id"),
                    rs.getDate("timer"),
                );
                resultSet.add(result);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("调用存储过程异常");
        }
        finally {
            if(cs != null){
                cs.close();
            }
            jdbcUtil.close(con);
        }
        return resultSet;
    }
posted @ 2018-12-20 21:13  2020张念磊要加油  阅读(446)  评论(0编辑  收藏  举报