本示例说明如何调用存储过程,该存储过程返回查询执行结果的结果集。
package org.nhooo.example.jdbc; import java.sql.CallableStatement; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; public class CallableStatementExample { private static final String URL = "jdbc:mysql://localhost/nhooo"; private static final String USERNAME = "root"; private static final String PASSWORD = ""; public static void main(String[] args) { try (Connection connection = DriverManager.getConnection(URL, USERNAME, PASSWORD)) { //准备调用sored过程。此SP需要 // 一个IN参数 String query = "call GetProductByPrice(?)"; CallableStatement cb = connection.prepareCall(query); // 设置输入参数 cb.setDouble(1, 40d); // 执行查询 ResultSet rs = cb.executeQuery(); while (rs.next()) { System.out.println("Product: " + rs.getString(1)); } } catch (SQLException e) { e.printStackTrace(); } } }
这是我们在上面的示例中使用的存储过程脚本。
DELIMITER ;; DROP PROCEDURE IF EXISTS GetProductByPrice;; CREATE PROCEDURE GetProductByPrice(IN product_price DECIMAL) BEGIN SELECT name FROM products WHERE price = product_price; END;; DELIMITER ;
Maven依赖
<!-- https://search.maven.org/remotecontent?filepath=mysql/mysql-connector-java/8.0.17/mysql-connector-java-8.0.17.jar --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.17</version> </dependency>