【JDBC】获取自动生成的主键

1.在开发的逻辑中经常会用到要获取主键信息的情况,比如新用户注册之后,要完善个人信息等。就需要在注册成功save之后,获取到给用户分配的id信息,以保证update的操作。

2.如何在JDBC中保存数据的时候获取自动生成的主键呢?

----------------------------------------------------------------------

Statement方式:

int executeUpdate(String sql,  int autoGeneratedKeys):执行SQL:

         参数:autoGeneratedKeys,是否需要返回自动生成的主键.常量值:Statement.RETURN_GENERATED_KEYS.

ResultSet getGeneratedKeys():获取自动生成的主键

示列代码如下:

    @Test
    public void statementTest() throws Exception {
        String sql = "insert into student (name, age) values ('zhangsan', 30)";
        Connection connection = JdbcUtil.getConn();
        Statement statement = connection.createStatement();
        // statement.executeUpdate(sql);
        statement.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS);
        ResultSet resultSet = statement.getGeneratedKeys();
        if (resultSet.next()) {
            Long id = resultSet.getLong(1);
            System.out.println(id);
        }
        JdbcUtil.close(connection, statement, null);
    }

-----------------------------------------------------------------------------

PreparedStatement方式:

PreparedStatement prepareStatement(String sql,int autoGeneratedKeys)  :

创建PreparedStatement对象,病指定是否需要返回生成的主键. 常量值:Statement.RETURN_GENERATED_KEYS

示列代码:

public class PreparedStatementTest {
    @Test
    public void preparedStatement() throws Exception {
        String sql = "insert into student (name,age) values (?,?)";
        Connection connection = JdbcUtil.getConn();
        PreparedStatement preparedStatement = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
        preparedStatement.setString(1, "张三");
        preparedStatement.setInt(2, 24);
        preparedStatement.executeUpdate();
        ResultSet resultSet = preparedStatement.getGeneratedKeys();
        if (resultSet.next()) {
            Long id = resultSet.getLong(1);
            System.out.println(id);
        }
        JdbcUtil.close(connection, preparedStatement, null);
    }
}

Hibernate中可以自动返回,底层已经封装好了。

  

posted @ 2017-04-19 16:08  Qingyun_Qearl  阅读(1042)  评论(0编辑  收藏  举报