数据库dataSource,执行存储过程

在META-INF 下配置 context.xml


<?xml version="1.0" encoding="UTF-8"?>


<Context reloadable="true">
  <Resource name="jdbc/xsgl" auth="Container" type="javax.sql.DataSource"
    maxActive="100" maxIdle="30" maxWait="10000"
    username="root" password="" driverClassName="com.mysql.jdbc.Driver"
    noAccessToProcedureBodies="false"
    url="jdbc:mysql://localhost:3306/xsgl"/>
</Context>


得到数据库的连接

Context context = new InitialContext();
DataSource dataSource = (DataSource)context.lookup("java:comp/env/jdbc/xsgl");
Connection connection = dataSource.getConnection();



对于存储过程的执行为

callableStatemenent 

对于没有 out 参数的存储过程,里面如果有select 等返回语句,可以和执行sql  语句一样直接得到 ResultSet 进行读取结果

但,如果存储过程中有 out 参数,如果下面的例子‘

create procedure getInfo(in sid varchar(10) ,out user varchar(10),out pass varchar(10))

begin 

select username,password into user,pass from student where id = sid

end;

其是将得到的值直接放入到 out  类型的参数中

那么前面用 java 在取出 out 类型的参数就可以这样:


Context context = new InitialContext();
DataSource dataSource = (DataSource)context.lookup("java:comp/env/jdbc/xsgl");
Connection connection = dataSource.getConnection();
String sql = "{call getinfo(?,?,?)}";
CallableStatement callableStatement = connection.prepareCall(sql);
callableStatement.setString("sid","1");
callableStatement.registerOutParameter(2,Types.VARCHAR);
callableStatement.registerOutParameter(3,Types.VARCHAR);
ResultSet rs = callableStatement.executeQuery();
String username = callableStatement.getString(2);
String password = callableStatement.getString(3);
System.out.println(username);
System.out.println(password);

在执行 callableStatement 前,如果有sql 中有 out 类型的参数,那么就要先注册 out 类型的参数的类型

在执行完成后并不在 ResultSet 中进行读取结果,

而是 callableStatement 中直接读取参数为out 类型的参数的值 




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值