jdbc调用mysql存储过程实现代码
程序员文章站
2024-02-21 21:58:52
1. 创建存储过程 建立一个mysql的存储过程 add_pro 复制代码 代码如下: delimiter // drop procedure add_pro // cre...
1. 创建存储过程
建立一个mysql的存储过程 add_pro
delimiter //
drop procedure add_pro //
create procedure add_pro(a int , b int , out sum int )
begin
set sum = a * b;
end;
//
2. 调用存储过程
package com.zhanggaosong;
import java.sql.callablestatement;
import java.sql.connection;
import java.sql.drivermanager;
import java.sql.types;
public class callablestatementtest {
public static final string driver_class = "com.mysql.jdbc.driver";
public static final string url = "jdbc:mysql://127.0.0.1:3306/test";
public static final string username = "root";
public static final string password = "123456";
public static void main(string[] args) throws exception {
class.forname(driver_class);
connection connection = drivermanager.getconnection(url, username,
password);
string sql = "{call add_pro(?,?,?)}"; //调用存储过程
callablestatement cstm = connection.preparecall(sql); //实例化对象cstm
cstm.setint(1, 122);
cstm.setint(2, 2); //
cstm.registeroutparameter(3, types.integer); // 设置返回值类型
cstm.execute(); // 执行存储过程
system.out.println(cstm.getint(3));
cstm.close();
connection.close();
}
}
建立一个mysql的存储过程 add_pro
复制代码 代码如下:
delimiter //
drop procedure add_pro //
create procedure add_pro(a int , b int , out sum int )
begin
set sum = a * b;
end;
//
2. 调用存储过程
复制代码 代码如下:
package com.zhanggaosong;
import java.sql.callablestatement;
import java.sql.connection;
import java.sql.drivermanager;
import java.sql.types;
public class callablestatementtest {
public static final string driver_class = "com.mysql.jdbc.driver";
public static final string url = "jdbc:mysql://127.0.0.1:3306/test";
public static final string username = "root";
public static final string password = "123456";
public static void main(string[] args) throws exception {
class.forname(driver_class);
connection connection = drivermanager.getconnection(url, username,
password);
string sql = "{call add_pro(?,?,?)}"; //调用存储过程
callablestatement cstm = connection.preparecall(sql); //实例化对象cstm
cstm.setint(1, 122);
cstm.setint(2, 2); //
cstm.registeroutparameter(3, types.integer); // 设置返回值类型
cstm.execute(); // 执行存储过程
system.out.println(cstm.getint(3));
cstm.close();
connection.close();
}
}
上一篇: 路由器ACL