JDBC获取主键和调用存储过程

作者: 小小蒜头 | 来源:发表于2017-09-26 22:15 被阅读37次

获得数据库自动生成的主键:

主代码:prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
'ResultSet.getGeneratedKeys();//得到插入行的主键'

建表:

create table testprimarykey(
    id int primary key auto_increment,
    name varchar(40)
);

测试:

@Test
    public void testPrimaryKey() {
        Connection conn = null;
        //用Statement去做
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            conn = JdbcUtils.getConnection();
            String sql = "insert into testprimarykey(name) values('aaa')";
            ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
            ps.executeUpdate();
            //得到生成的键
            rs = ps.getGeneratedKeys();
            if (rs.next()){
               int id =  rs.getInt(1);
                System.out.println(id);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            JdbcUtils.release(conn, ps, rs);
        }
    }

JDBC调用存储过程

得到CallableStatement,并调用存储过程:

CallableStatement  cStmt = conn.prepareCall("{call demoSp(?,?)}");

设置参数,注册返回值,得到输出:

cStmt.setString(1, "qwer");
cStmt.registerOutParameter(2, Types.VARCHAR);
cStmt.execute();
System.out.println(cStmt.getString(2));

在MySQL中创建一个存储过程:

delimiter $$

CREATE PROCEDURE demoSp(IN inputParam VARCHAR(255), INOUT inOutParam varchar(255))
BEGIN
    SELECT CONCAT('zyxw---', inputParam) into inOutParam;
END $$

delimiter ;

测试

 @Test
    public void testProcedure() {
        Connection conn = null;
        //用Statement去做
        CallableStatement cStmt = null;
        ResultSet rs = null;

        //第一个参数替换掉,执行后,结果作为第二个参数返回。mysql不知道返回类型是什么
        try {
            conn = JdbcUtils.getConnection();
            cStmt = conn.prepareCall("{call demoSp(?,?)}");
            cStmt.setString(1, "qwer");
            cStmt.registerOutParameter(2, Types.VARCHAR);
            cStmt.execute();
            System.out.println(cStmt.getString(2));
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            JdbcUtils.release(conn, cStmt, rs);
        }
    }

相关文章

网友评论

    本文标题: JDBC获取主键和调用存储过程

    本文链接:https://www.haomeiwen.com/subject/twdsextx.html