sql:CallableStatement执行存储过程
2024-10-01 04:32:22
/**
* 使用CablleStatement调用存储过程
* @author APPle
*
*/
public class Demo1 { /**
* 调用带有输入参数的存储过程
* CALL pro_findById(4);
*/
@Test
public void test1(){
Connection conn = null;
CallableStatement stmt = null;
ResultSet rs = null;
try {
//获取连接
conn = JdbcUtil.getConnection(); //准备sql
String sql = "CALL pro_findById(?)"; //可以执行预编译的sql //预编译
stmt = conn.prepareCall(sql); //设置输入参数
stmt.setInt(1, 6); //发送参数
rs = stmt.executeQuery(); //注意: 所有调用存储过程的sql语句都是使用executeQuery方法执行!!! //遍历结果
while(rs.next()){
int id = rs.getInt("id");
String name = rs.getString("name");
String gender = rs.getString("gender");
System.out.println(id+","+name+","+gender);
} } catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
} finally {
JdbcUtil.close(conn, stmt ,rs);
}
} /**
* 执行带有输出参数的存储过程
* CALL pro_findById2(5,@NAME);
*/
@Test
public void test2(){
Connection conn = null;
CallableStatement stmt = null;
ResultSet rs = null;
try {
//获取连接
conn = JdbcUtil.getConnection();
//准备sql
String sql = "CALL pro_findById2(?,?)"; //第一个?是输入参数,第二个?是输出参数 //预编译
stmt = conn.prepareCall(sql); //设置输入参数
stmt.setInt(1, 6);
//设置输出参数(注册输出参数)
/**
* 参数一: 参数位置
* 参数二: 存储过程中的输出参数的jdbc类型 VARCHAR(20)
*/
stmt.registerOutParameter(2, java.sql.Types.VARCHAR); //发送参数,执行
stmt.executeQuery(); //结果不是返回到结果集中,而是返回到输出参数中 //得到输出参数的值
/**
* 索引值: 预编译sql中的输出参数的位置
*/
String result = stmt.getString(2); //getXX方法专门用于获取存储过程中的输出参数 System.out.println(result); } catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
} finally {
JdbcUtil.close(conn, stmt ,rs);
}
}
}
最新文章
- javascript 类型转换。
- ISP路由表分发中的AS与BGP
- 微服务(Microservices)——Martin Flower【翻译】
- 浅谈html5 响应式布局
- onkeyup,onkeydown和onkeypress
- jQuery中ajax应用
- aop aspect
- android 组件设置屏幕大小
- MySQL sql 执行步骤
- 分享注册AltiumDesignerLive官网账号注册方法教程
- int装箱比较
- Harbor--企业级项目管理
- Linux 第七周实验 及总结
- BZOJ1330 : Editing a Book
- 通过官方API结合源码,如何分析程序流程
- python:extend (扩展) 与 append (追加) 之间的天与地
- c# 线程同步各类锁
- vue之过滤器
- 49.纯 CSS 创作一支诱人的冰棍
- IntelliJ中的main函数、for循环、System.out.println()快捷键