• 如何使用 JDBC 调用存储在数据库中的函数或存储过程


    JDBC调用存储过程
    步骤:
    1 通过Connection对象的prepareCall()方法创建一个CallableStatement对象的实例。在使用Connection对象的prepareCall()方法时,需要传入一个String类型的字符串,该字符串用于指明如何调用存储过程
    {?= call <procedure-name>[(<arg1>,<arg2>, ...)]}
    {call <procedure-name>[(<arg1>,<arg2>, ...)]}

    2 通过CallableStatement对象的registerOutParameter()方法注册OUT参数
    3 通过CallableStatement对象的setXxx()方法设定IN或IN OUT参数
    若想将参数默认值设为Null,可以使用setNull()方法
    4 通过CallableStatement对象的execute()方法执行存储过程
    5 如果所调用的是带返回参数的存储过程,还需要通过CallableStatement对象的getXxx()方法获取其返回值
    注:通过数据字典查看存储过程或函数的定义

    select text from user_source where lower(name)='add_fun';
    调用函数:

    package com.atguigu.jdbc;

    import static org.junit.Assert.*;

    import java.sql.CallableStatement;
    import java.sql.Connection;
    import java.sql.SQLException;
    import java.sql.Types;

    import javax.sql.DataSource;

    import org.junit.Test;

    import com.mchange.v2.c3p0.ComboPooledDataSource;

    public class JDBCTest {

    /**
    * 如何使用 JDBC 调用存储在数据库中的函数或存储过程
    */
    @Test
    public void testCallableStatment() {

    Connection connection = null;
    CallableStatement callableStatement = null;

    try {
    connection = JDBCTools.getConnection();

    // 1. 通过 Connection 对象的 prepareCall()
    // 方法创建一个 CallableStatement 对象的实例.
    // 在使用 Connection 对象的 preparedCall() 方法时,
    // 需要传入一个 String 类型的字符串, 该字符串用于指明如何调用存储过程.
    String sql = "{?= call sum_salary(?, ?)}";
    callableStatement = connection.prepareCall(sql);

    // 2. 通过 CallableStatement 对象的
    //reisterOutParameter() 方法注册 OUT 参数.
    callableStatement.registerOutParameter(1, Types.NUMERIC);
    callableStatement.registerOutParameter(3, Types.NUMERIC);

    // 3. 通过 CallableStatement 对象的 setXxx() 方法设定 IN 或 IN OUT 参数. 若想将参数默认值设为
    // null, 可以使用 setNull() 方法.
    callableStatement.setInt(2, 80);

    // 4. 通过 CallableStatement 对象的 execute() 方法执行存储过程
    callableStatement.execute();

    // 5. 如果所调用的是带返回参数的存储过程,
    //还需要通过 CallableStatement 对象的 getXxx() 方法获取其返回值.
    double sumSalary = callableStatement.getDouble(1);
    long empCount = callableStatement.getLong(3);

    System.out.println(sumSalary);
    System.out.println(empCount);

    } catch (Exception e) {
    e.printStackTrace();
    } finally {
    JDBCTools.releaseDB(null, callableStatement, connection);
    }


    }

    @Test
    public void testC3P0() throws SQLException {
    DataSource dataSource = new ComboPooledDataSource("c3p0");

    System.out.println(dataSource.getConnection());
    }

    }

  • 相关阅读:
    java继承
    c#中委托和事件区别
    c#委托中的匿名方法和lambda表达式
    c#中内置委托
    iOS消息推送获取不到deviceToken解决方案
    python+appium+iOS自动化测试case如何写?
    Xcode查看iOS崩溃与崩溃日志分析
    iOS性能检测工具instrunments简单介绍
    python实现使用代码进行代理配置
    python+locust性能测试-最简单的登录点击次数
  • 原文地址:https://www.cnblogs.com/xiaona19841010/p/5223779.html
Copyright © 2020-2023  润新知