Java如何执行存储过程?
存储过程" title="存储过程">存储过程是用户生成的函数或过程,它们一旦在数据库中创建,便可以由诸如Java应用程序之类的客户端应用程序调用。在此示例中,我们将演示如何使用JDBCjava.sql.CallableStatement调用存储过程。此示例中的存储过程仅用于从products表中选择记录。
package org.nhooo.example.jdbc;import java.sql.*;
public class CallableStatementDemo {
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以执行GetAllProducts()
// 程序。
CallableStatement stmt =
connection.prepareCall("{CALL GetAllProducts()}");
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
System.out.println(rs.getLong("id") + "\t"
+ rs.getString("code") + "\t"
+ rs.getString("name") + "\t"
+ rs.getDouble("price"));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
下面是在上面的代码中执行的存储过程定义。
DELIMITER ;;CREATE PROCEDURE `GetAllProducts`()
BEGIN
SELECT * FROM products;
END;;
DELIMITER ;
运行代码片段时,结果将是这样的:
1 P0000001 UML Distilled 3rd Edition 25.03 P0000003 PHP Programming 20.0
4 P0000004 Longman Active Study Dictionary 40.0
5 P0000005 Ruby on Rails 24.0
6 P0000006 Championship Manager 0.0
7 P0000007 Transport Tycoon Deluxe 0.0
8 P0000008 Roller Coaster Tycoon 3 0.0
9 P0000009 Pro Evolution Soccer 0.0
10 P0000010 Data Structures, Algorithms 50.99
Maven依赖
<!-- https://search.maven.org/remotecontent?filepath=mysql/mysql-connector-java/8.0.17/mysql-connector-java-8.0.17.jar --><groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.17</version>
</dependency>
以上是 Java如何执行存储过程? 的全部内容, 来源链接: utcz.com/z/330741.html