码迷,mamicode.com
首页 > 数据库 > 详细

JDBC 存储过程

时间:2019-09-28 23:36:06      阅读:103      评论:0      收藏:0      [点我收藏+]

标签:exist   callable   RoCE   key   rest   utils   lis   generate   val   

存储过程

DROP PROCEDURE IF EXISTS `addUser`;
CREATE PROCEDURE `addUser` 
(in pname VARCHAR(45),in birthday date,in money float,out pid int)
BEGIN
  INSERT into `user`(name,birthday,money) VALUES(pname,birthday,money);
  SELECT LAST_INSERT_ID() into pid;
END;

java

package jdbc;

import java.sql.*;

public class PsTest {
    public static void main(String[] args) throws SQLException {
        ps();
    }

    static void ps() throws SQLException {
        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, 100.0f);
            cs.executeUpdate();
            int res = cs.getInt(4);
            System.out.println("res= " + res);

        } finally {
            JdbcUtils.free(rs, cs, conn);
        }
    }
}

 api

package jdbc;

import java.sql.*;

public class OtherApi {
    public static void main(String[] args) throws SQLException {
        int id = create();
        System.out.println(id);
    }

    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(‘name1‘,‘1987-01-01‘,400)";
            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);
        }
    }
}

 

JDBC 存储过程

标签:exist   callable   RoCE   key   rest   utils   lis   generate   val   

原文地址:https://www.cnblogs.com/kikyoqiang/p/11605368.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!