如何使用JDBC调用存储在数据库中的函数或存储过程:
* 1.通过COnnection对象的prepareCall()方法创建一个CallableStatement
* 对象的实例,在使用Connection对象的prepareCall() 方法时,需要传入一个String类型的字符串,
* 该字符串用于指明如何调用存储过程
* 2.通过CallableStatement对象的registerOutParameter() 方法注册Out参数
* 3.通过CallableStatement对象的setXxx()方法设定IN或In out
* 参数,若想将参数设为null,可以使用setNUll()
* 4.通过CallableStatement对象的execute()方法执行存储过程
* 5.如果所调用的是带返回参数的存储过程没还需要通过CallableStatement对象的getXxx()函数进行获取
具体的代码实现:
@Test
public void testCallableStatement() {
Connection connection = null;
/**
* 调用存储函数 1.{?= call <procedure-name>[(<arg1>,<arg2>, ...)]}
* 调用存储过程 2.{call <procedure-name>[(<arg1>,<arg2>, ...)]}
*/
// 调用存储函数和调用存储过程,一个sql语句的区别
String sql = "{?= call <procedure-name>[(<arg1>,<arg2>, ...)]}";
CallableStatement callableStatement = null;
try {
connection = JDBCTools.getConnection();
/*
* 1.通过COnnection对象的prepareCall()方法创建一个CallableStatement
* 对象的实例,在使用Connection对象的prepareCall() 方法时,需要传入一个String类型的字符串,
* 该字符串用于指明如何调用存储过程
*/
callableStatement = connection.prepareCall(sql);
/*
* 2.通过CallableStatement对象的registerOutParameter() 方法注册Out参数
*/
callableStatement.registerOutParameter(1, Types.NUMERIC);
callableStatement.registerOutParameter(3, Types.NUMERIC);
/*
* 3.通过CallableStatement对象的setXxx()方法设定IN或In out
* 参数,若想将参数设为null,可以使用setNUll()
*/
callableStatement.setInt(2, 80);
/* 4.通过CallableStatement对象的execute()方法执行存储过程 */
callableStatement.execute();
/*
* 5.如果所调用的是带返回参数的存储过程没还需要通过CallableStatement对象的getXxx()
*/
double sumSalary = callableStatement.getDouble(1);
long empCount = callableStatement.getLong(3);
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCTools.release(null, callableStatement, connection);
}
}
调用函数和存储过程的sql语句的区别:
* 调用存储函数 1.{?= call <procedure-name>[(<arg1>,<arg2>, ...)]}
* 调用存储过程 2.{call <procedure-name>[(<arg1>,<arg2>, ...)]}
这个知识点暂时没用到,先做下笔记,待以后用到以后再深入研究,JDBC的学习暂时告一段落,开启新的学习征程!