java 调用 mysql 存储过程
时间: 2023-11-11 10:04:54 浏览: 142
以下是Java调用MySQL存储过程的步骤:
1.创建存储过程
在MySQL中创建存储过程,例如:
```mysql
CREATE PROCEDURE `get_user`(IN id INT, OUT name VARCHAR(20), OUT age INT)
BEGIN
SELECT user_name, user_age INTO name, age FROM user WHERE user_id = id;
END
```
2.在Java中连接到MySQL数据库
使用JDBC连接到MySQL数据库,例如:
```java
String url = "jdbc:mysql://localhost:3306/test";
String user = "root";
String password = "123456";
Connection conn = DriverManager.getConnection(url, user, password);
```
3.调用存储过程
使用CallableStatement调用存储过程,例如:
```java
String sql = "{call get_user(?,?,?)}";
CallableStatement cstmt = conn.prepareCall(sql);
cstmt.setInt(1, 1);
cstmt.registerOutParameter(2, Types.VARCHAR);
cstmt.registerOutParameter(3, Types.INTEGER);
cstmt.execute();
String name = cstmt.getString(2);
int age = cstmt.getInt(3);
```
4.处理存储过程的结果
根据需要处理存储过程的结果,例如:
```java
System.out.println("Name: " + name);
System.out.println("Age: " + age);
```
阅读全文