Java如何在CallableStatement中注册参数?
本示例说明如何使用CallableStatement.registerOutParameter()方法调用注销用于执行存储过程的参数。 我们必须在执行查询之前注册out参数。 registerOutParameter()方法采用两个参数,参数的索引和out参数的sql数据类型。
package org.nhooo.example.jdbc; import java.sql.*; public class RegisterOutParameter { 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)) { // 创建一个CallableStatement来执行存储的 // 程序 String query = "call GetDetailByName(?, ?, ?)"; CallableStatement cb = connection.prepareCall(query); // 设置输入参数 cb.setString(1, "Ruby on Rails"); // 注册输出参数 cb.registerOutParameter(2, Types.VARCHAR); cb.registerOutParameter(3, Types.DECIMAL); // 执行查询 cb.executeQuery(); // 获取查询结果输出 System.out.println("Name : " + cb.getString(1)); System.out.println("Code : " + cb.getString(2)); System.out.println("Price : " + cb.getBigDecimal(3)); } catch (SQLException e) { e.printStackTrace(); } } }
这是我们在上面的代码中调用的MySQL存储过程。
DELIMITER ;; DROP PROCEDURE IF EXISTS `GetDetailByName`;; CREATE PROCEDURE `GetDetailByName`(INOUT product_name VARCHAR(50), OUT product_code VARCHAR(10), OUT product_price DECIMAL(10, 2)) BEGIN SELECT code INTO product_code FROM products WHERE name = product_name; SELECT price INTO product_price FROM products WHERE name = product_name; 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>