mysql建立存储过程的语法及其模板:
DELIMITER // /*注意点1:必须以[delimiter 标识符]开始*/ CREATE PROCEDURE collectionexp(IN NUid VARCHAR(28),IN NCid VARCHAR(32),IN NType VARCHAR(20),IN NTime VARCHAR(20),OUT flag INT) BEGIN /*注意点2:必须把所有变量定义好后才可以执行赋值操作*/ DECLARE state VARCHAR(5); /*注意点3:定义变量时,变量前无需带@符号,语句都需要加分号*/ DECLARE chooseflag INT; DECLARE ccount INT; DECLARE nowcount INT; /*注意点4:给变量赋值时,变量前必须带@符号*/ /*注意点5:如果结果是一条sql语句,必须用括号*/ SET @state=(SELECT Course_state FROM course WHERE Cid=NCid); SET @chooseflag=(SELECT COUNT(*) FROM choosecourse WHERE Uid=NUid); SET @ccount=(SELECT Collection_num FROM course WHERE Cid=NCid); SET @nowcount=@ccount+1; IF @chooseflag=0 THEN INSERT INTO choosecourse VALUES(NUid,NCid,0,1,0,'1',@state,NTime,''); UPDATE course SET Collection_num=@nowcount WHERE Cid=NCid; SET flag=1; /*注意点6:给输出参数赋值时,不需要加@符号*/ END IF; /*注意点7:endif结束也需要加分号*/ IF @chooseflag=1 THEN UPDATE choosecourse SET Collection=1 WHERE Cid=NCid; UPDATE course SET Collection_num=@nowcount WHERE Cid=NCid; SET flag=1; ELSE SET flag=0; END IF; END // /*注意点8:以什么标识符开始,就要以什么标识符结束*/
javaTemplate使用存储过程的模板:
//1.存储过程有返回值 JdbcTemplate jdbcTemplate = new JdbcTemplate(注入数据源); public int test(final int id) { return jdbcTemplate.execute( new CallableStatementCreator() { public CallableStatement createCallableStatement(Connection con) throws SQLException { String storedProc = "{call 存储过程名(?,?)}"; // 调用的sql 这个就是写在mysql里的存储过程,存储过程里的输出参数也需要一个占位符 CallableStatement cs = con.prepareCall(storedProc); // 设置输入参数的下标和值 cs.setString(1, id); // 设置输出参数的下标和返回值类型 cs.registerOutParameter(2, Types.INTEGER); return cs; } }, new CallableStatementCallback() { public Object doInCallableStatement(CallableStatement cs) throws SQLException, DataAccessException { //执行存储过程 cs.execute(); // 获取输出参数的值 return cs.getInt(2); } }); } //2.存储过程无返回值 static JdbcTemplate jdbc = new JdbcTemplate(JDBCUtils.getDataSource(); public class NettyDao { public void upNewData( String 参数1, String 参数2, String 参数3) { jdbc.execute("call 存储过程名(参数1,参数2,参数3)"); } }
测试案例:
public class Test { static JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource()); public static int test(final int id) { return (int) template.execute( new CallableStatementCreator() { public CallableStatement createCallableStatement(Connection con) throws SQLException { String storedProc = "{CALL collectionexp(?,?,?,?,?)}"; CallableStatement cs = con.prepareCall(storedProc); cs.setString(1,String.valueOf(id)); cs.setString(2,String.valueOf(id)); cs.setString(3,String.valueOf(id)); cs.setString(4,String.valueOf(id)); cs.registerOutParameter(5, Types.INTEGER); return cs; } }, new CallableStatementCallback() { public Object doInCallableStatement(CallableStatement cs) throws SQLException, DataAccessException { cs.execute(); return cs.getInt(5); } }); } public static void main(String[] args) { int res=test(1); System.out.println(res); } }