DELIMITER $$ DROP PROCEDURE IF EXISTS `jdbc`.`addUser` $$
CREATE PROCEDURE `jdbc`.`addUser` (in pname varchar(45),in birthday date,in money float,out pid int)
BEGIN
insert into user(name,birthday,money) value(pname,birthday,money);
select last_insert_id() into pid;
END $$ DELIMITER ;
addUser
package it.cast.jdbc; import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types; public class PsTest { public static void main(String[] args) throws SQLException {
create();
} static void ps(){
Connection conn = null;
CallableStatement cs = null;
ResultSet rs = null; try {
conn = jdbcUtils.getConnection(); String sql = "{ call addUser(?,?,?,?)}";
cs = conn.prepareCall(sql);
cs.registerOutParameter(4, Types.INTEGER);//输出参数需要注册
cs.setString(1, "ps name");
cs.setDate(2, new java.sql.Date(System.currentTimeMillis()));
cs.setFloat(3, 100f); cs.executeUpdate();
int id = cs.getInt(4); System.out.println("id="+id);
} catch (SQLException e) {
e.printStackTrace();
}finally{
jdbcUtils.free(rs, cs, conn);
}
} static int create() throws SQLException{
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null; try {
conn = jdbcUtils.getConnection(); String sql = "insert into user(name,birthday,money) values('zero','1987-01-01','4000')";
ps = conn.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);//返回插入数据的主键
ps.executeUpdate(); rs = ps.getGeneratedKeys(); int id = 0;
if(rs.next()){
id = rs.getInt(1);
} return id;
} finally{
jdbcUtils.free(rs, ps, conn);
} } }
PsTest