java的存储过程
时间: 2023-07-01 15:26:57 浏览: 50
Java中的存储过程是一段预先编译好的SQL代码,可以在需要时调用。存储过程通常在服务器端执行,可以大大减少客户端与服务器之间的数据传输量,提高数据库的执行效率。在Java中,可以使用JDBC(Java Database Connectivity) API来调用存储过程。
下面是一个简单的Java程序示例,用于调用MySQL数据库中的一个存储过程:
```java
import java.sql.*;
public class CallStoredProcedure {
public static void main(String[] args) {
try {
// 加载MySQL JDBC驱动程序
Class.forName("com.mysql.jdbc.Driver");
// 连接到数据库
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "root", "password");
// 创建CallableStatement对象,用于调用存储过程
CallableStatement cs = conn.prepareCall("{call my_stored_procedure(?, ?, ?)}");
// 设置存储过程参数
cs.setInt(1, 100);
cs.setString(2, "John");
cs.setString(3, "Doe");
// 执行存储过程
cs.execute();
// 获取存储过程的输出参数
int result = cs.getInt(1);
// 关闭连接和Statement对象
cs.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
在上面的示例中,我们通过JDBC API连接到MySQL数据库,并使用CallableStatement对象调用了一个名为my_stored_procedure的存储过程。存储过程有三个输入参数,分别为整型、字符串和字符串类型,然后执行存储过程并获取其输出参数。最后,关闭连接和Statement对象。