JDBC-调用函数&存储过程

JDBC_调用函数&存储过程

  • 在这里插入图片描述

  • 调用函数用{?=call<procedure-name>[(<args1>,<args2>,...)]}

    • 实例代码

      /**
      	 * 如何使用 JDBC 调用存储在数据库中的函数或存储过程
      	 */
      	@Test
      	public void testCallableStatment() {
      
      		Connection connection = null;
      		CallableStatement callableStatement = null;
      
      		try {
      			connection = (Connection) JDBCTools.getConnection();
      
      			// 1. 通过 Connection 对象的 prepareCall()方法
      			// 创建一个 CallableStatement 对象的实例.
      			// 在使用 Connection 对象的 preparedCall() 方法时,
      			// 需要传入一个 String 类型的字符串, 该字符串用于指明如何调用存储过程.
      			String sql = "{?= call sum_salary(?, ?)}";
      			callableStatement = (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);
      		}
      	}
      

      注:此处调用的是Oracle数据库,所以xml文件中 要改变

      <?xml version="1.0" encoding="UTF-8"?>
      
      <c3p0-config>
      
        <named-config name="c3p0"> 
      	
          <property name="user">scott</property>
          <property name="jdbcUrl">jdbc:oracle:thin:@localhost:1521:orcl</property>
          <property name="driverClass">oracle.jdbc.driver.OracleDriver</property>
          <property name="password">java</property>
      
          <property name="acquireIncrement">5</property>
          <property name="initialPoolSize">5</property>
          <property name="minPoolSize">5</property>
          <property name="maxPoolSize">10</property>
      
          <property name="maxStatements">20</property> 
          <property name="maxStatementsPerConnection">5</property>
      
        </named-config>
      
      </c3p0-config>
      
  • 调用存储过程用{call<procedure-name>[(<args1>,<args2>,...)]}

    其余过程与调用函数一样

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值