1.函数和存储过程相似,只是多了返回值声明.
2.创建函数
mysql>create function sf_add(a int ,b int) returns int
begin
return a + b ;
end
//
3.显式创建的函数
mysql>show function status --
mysql>show function status like '%add%' --
mysql>select sf_add(1,2)
4.java调用函数
@Test
public void testFunction() throws Exception {
long start = System.currentTimeMillis();
//创建连接
String driverClass = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/test";
String username = "root";
String password = "root";
Class.forName(driverClass);
Connection conn = DriverManager.getConnection(url, username, password);
//关闭自动提交
conn.setAutoCommit(false);
//创建可调用语句,调用存储过程
CallableStatement cst = conn.prepareCall("{? = call sf_add(?,?)}");
cst.setInt(2,100);
cst.setInt(3,200);
cst.registerOutParameter(1,Types.INTEGER);
//注册输出参数类型
cst.execute();
System.out.println(cst.getInt(1));
conn.commit();
conn.close();
System.out.println(System.currentTimeMillis() - start);
}