在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 类型的参数的值