获取mysql自主生成的主键

一.sql语句

CREATE TABLE `testgeneratedkeys` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(20) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

二.测试代码

public class JdbcGeneratedKeys {

    @Test
    public void test() {
        Connection conn = null;
        PreparedStatement st = null;
        ResultSet rs = null;
        try{
            conn = JdbcUtils.getConnection();
            String sql = "insert into testgeneratedkeys(name) values(?)";
            //使用mysql-connector-java-5.1.33-bin.jar作为驱动,添加参数Statement.RETURN_GENERATED_KEYS
            //mysql-connector-java-3.0.10.jar作为驱动,可添加可不添加。
            st = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
            st.setString(1, "哈哈哈哈哈");
            st.executeUpdate();
            //获取数据库自动生成的主键
            rs = st.getGeneratedKeys();
            if(rs.next()){
                System.out.println(rs.getInt(1));
            }
        }catch (Exception e) {
            e.printStackTrace();
        }finally{
            JdbcUtils.release(conn, st, rs);
        }
    }
}

获取的就是刚刚生成的主键!!!

posted @ 2018-08-23 16:51  何其小静  阅读(323)  评论(0编辑  收藏  举报