jdbc调用存储过程和存储函数
1jdbc总结(模板):
a、导入驱动包:class.forName(“驱动类”)
b、与数据库建立连接(connection = DriverManager.getConnection(url, user, password);
c、通过connection,获取操作数据库的对象Statetment/prepareStatement/callStatement
stmt = connection.createStatement() ;
d、查询(处理结果集):
while(rs.next()) { int num = rs.getInt("num"); String name = rs.getString("name"); int age = rs.getInt("age"); System.out.println("num---"+num+"//name---"+name+"//age----"+age); }
catch异常:
try{.... }catch(SQLException e) { e.printStackTrace(); }catch(ClassNotFoundException e) { e.printStackTrace(); }catch(Exception e) { e.printStackTrace(); }//具体问题具体分析
finally{
if(rs!=null)rs.close();
if(stmt!= null)stmt.close();
if(connection!= null)connection.close();} //打开顺序与关闭顺序相反
--jdbc中,除了Class.forName()抛出ClassNotFoundException e之外,其余都是SQLException e。
========================================================================================
CallableStatement:调用存储过程、存储函数
connection.prepareCall(存储过程、存储函数名);
参数格式:
过程:(无返回值,用out代替)
{call 存储过程名(参数列表)}
函数:(有返回值return)
{ = call 存储函数名(参数列表)}
存储过程
package Mydemo; import java.sql.CallableStatement; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; import java.sql.Types; public class callableStatement { static CallableStatement cstmt = null; static Connection cont = null; public static void invoke() { String url ="jdbc:sqlserver://localhost:0;DatabaseName=test"; String user = "sa"; String password = "123456"; try { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); cont = DriverManager.getConnection(url, user, password); cstmt = cont.prepareCall("{call 存储过程(?,?,?)}"); cstmt.setInt(1, 10); cstmt.setInt(2, 10); cstmt.registerOutParameter(3, Types.INTEGER); cstmt.execute();//num1+num2,execute()之前处理输入参数 //设置输出参数的类型 cstmt.getInt(3); int resuult = cstmt.getInt(3);//获取输出结果 System.out.println("sdsda"+resuult); }catch(ClassNotFoundException e) { e.printStackTrace(); }catch(SQLException e) { e.printStackTrace(); }finally { try{ if(cstmt!=null)cstmt.close(); if(cont!=null)cont.close(); }catch(SQLException e) { e.printStackTrace(); } } } public static void main(String[] args) { invoke(); } }
存储函数与存储过程类似,(使用时更改的部分)
存储函数:
cstmt = cont.prepareCall("{? = call 存储过程(?,?)}"); cstmt.setInt(2, 10); cstmt.setInt(3, 10); cstmt.registerOutParameter(13, Types.INTEGER); int resuult = cstmt.getInt(3);//获取输出结果 System.out.println("sdsda"+resuult);
存储过程
cstmt = cont.prepareCall("{call 存储过程(?,?,?)}"); cstmt.setInt(1, 10); cstmt.setInt(2, 10); cstmt.registerOutParameter(3, Types.INTEGER); cstmt.execute();//num1+num2,execute()之前处理输入参数 //设置输出参数的类型 cstmt.getInt(3); int resuult = cstmt.getInt(3);//获取输出结果