有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在插入一行之后获取序列id?

我有一个表,在PostgreSQL中,行“id”(主键)默认设置为serial。我通过调用

session.getCurrentSession().createSQLQuery("some insert query") 

不向id中添加任何值,因为它默认设置为串行

如何检索刚刚插入的行的“id”


共 (3) 个答案

  1. # 1 楼答案

    JDBC语句can return the generated keys。例如,如果表中有一个类型为serial(可能是PK)的id列,但在下面的insert SQL中没有提到,则该列的生成值可以通过以下方式获得:

    PreparedStatement s = connection.createStatement
      ("INSERT INTO my_table (c,d) VALUES (1,2)", 
        Statement.RETURN_GENERATED_KEYS);
    s.executeUpdate(); 
    ResultSet keys = s.getGeneratedKeys();
    int id = keys.getInt(1); 
    

    这比稍后发送第二个查询以获取序列值或最大列值要快。另外,根据具体情况,这两种其他解决方案可能不是线程安全的

  2. # 2 楼答案

    因为它是串行的,所以可以使用select max(id) from tableName

         Using max(id) is a very bad idea. It will not give you the correct result 
        in case of multiple concurrent transactions. The only correct way is to use 
    curval() or the returning clause.
    

    posgresql中:顺便说一句,已经有一个stackoverflow-question存在

       `INSERT INTO tableName(id, name) VALUES(DEFAULT, 'bob') RETURNING id;`
    

    (还)

    获取特定序列:

    SELECT currval('name_of_your_sequence');

    从使用的最后一个序列中获取最后一个值:

    SELECT lastval();

    手册:http://www.postgresql.org/docs/current/static/functions-sequence.html

    对于PHP mysql用户:

    来自php。netclickhere

    <?php
    $link = mysqli_connect('localhost', 'mysql_user', 'mysql_password');
    if (!$link) {
        die('Could not connect: ' . mysqli::$connect_error() );
    }
    mysqli::select_db('mydb');
    
    mysqli::query("INSERT INTO mytable (product) values ('kossu')");
    printf("Last inserted record has id %d\n", mysqli::$insert_id());
    ?>
    

    但您需要为每个查询连接