---
title: "MySQL中使用存储过程[转]"
author: "java_lk"
date: "2008-05-23T13:20:55Z"
tags: []
slug: "mysql"
draft: false
lastmod: "2008-05-23T13:20:55Z"
id: 196053
url: "https://java-lk.iteye.com/blog/196053"
---

原文地址：http://www.javaresearch.org/article/33716.htm

使用CallableStatements执行存储过程

mysql版本:5.0
Connector/J的版本:3.1.1以上(java.sql.CallableStatement接口已完全实现,除了getParameterMetaData()方法)
MySQL的存储过程语法在MySQL参考手册的"存储过程和函数"一章.
http://www.mysql.com/doc/en/Stored_Procedures.html
下面是一个存储过程,返回一个inOutParam增1后的值,以ResultSet形式传入一个字符串参数inputParam.
CREATE PROCEDURE demoSp(IN inputParam VARCHAR(255), INOUT inOutParam INT)
BEGIN
DECLARE z INT;
SET z = inOutParam + 1;
SET inOutParam = z;
SELECT inputParam;
SELECT CONCAT('zyxw', inputParam);
END

要通过connector/J使用demoSp这个存储过程,要经过几个步骤:
1.Connection.prepareCall()


```java

import java.sql.CallableStatement; 
... 
// 
// Prepare a call to the stored procedure 'demoSp' 
// with two parameters 
// 
// Notice the use of JDBC-escape syntax ({call ...}) 
// 
CallableStatement cStmt = conn.prepareCall("{call demoSp(?, ?)}"); 
cStmt.setString(1, "abcdefg"); 

```


Connection.prepareCall()方法非常消耗资源,因为jdbc驱动通过元数据(metadata)的获取支持输出参数.出于执行效率的考虑,应该尽可能减少不必要的prepareCall调用,重用CallableStatement对象.

2.注册输出参数(如果有的话)

要得到输出参数的值(创建存储过程时设置的OUT和INOUT),JDBC要求这些参数必须要在数据库操作执行之前通过registerOutputPrameter()方法设置.

```java
import java.sql.Types; 
... 
// 
// 下面给出了设置输出参数的几个方法 
// 
// 注册第二个参数为输出参数 
// 
cStmt.registerOutParameter(2); 
// 
// 注册第二个参数为输出参数,设定getObject得到的返回值的类型为整型 
//  
cStmt.registerOutParameter(2, Types.INTEGER); 
// 
// 注册名为"inOutParam"的参数为输出参数 
// 
cStmt.registerOutParameter("inOutParam"); 
// 
// 注册名为"inOutParam"的参数为输出参数,设定getObject得到的返回值的类型为整型 
// 
cStmt.registerOutParameter("inOutParam", Types.INTEGER); 

```

3.设置输入参数(如果有的话)
类似PreparedStatement的设置参数方法.

```java
// 设置第一个参数值 
// 
cStmt.setString(1, "abcdefg"); 
// 
// 根据名字设置参数值 
// 
cStmt.setString("inputParameter", "abcdefg"); 
// 
// 根据索引值设置输入/输出参数 
// 
cStmt.setInt(2, 1); 
// 
// 根据参数名设置输入/输出参数 
//  
// 
cStmt.setInt("inOutParam", 1); 
... 

```

4.执行CallableStatement,获取结果集合或输出参数
尽管CallableStatement支持Statement接口的所有执行方法(executeUpdate(),executeQuery()或execute()),最具伸缩性的方法是execute(),因为你不需要知道是否这个存储过程返回结果集合.

```java
... 
boolean hadResults = cStmt.execute(); 
// 
// 处理返回的结果集合 
// 
while (hadResults) { 
ResultSet rs = cStmt.getResultSet(); 
//  
... 
hadResults = cStmt.getMoreResults(); 
} 
// 
// 获取输出参数,通过索引值或参数名 
// 
// 
int outputValue = cStmt.getInt(1);  
outputValue = cStmt.getInt("inOutParam");  


```