【问题标题】:How to get the serial id just after inserting a row? [duplicate]插入一行后如何获取序列号? [复制]
【发布时间】:2013-06-03 12:43:02
【问题描述】:

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

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

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

如何检索刚刚插入的行的 `id'?

【问题讨论】:

  • 从表中选择最大值(id)?
  • 你搜索了吗?上面的文章是我第一次搜索“postgresql jdbc 生成的密钥”。
  • 感谢@CraigRinger .. 成功了

标签: java hibernate postgresql


【解决方案1】:

JDBC 语句can return the generated keys。例如,如果表有一个 id 类型的 serial 列(可能是 PK),在下面的插入 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】:

    由于是串行的,你可以使用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 存在 BTW。

       `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.net clickhere

    <?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());
    ?>
    

    但您需要为每个查询连接。

    【讨论】:

    • 实际上我正在编写的代码是针对大量用户的。在这种情况下,可能会在毫秒内发生多次插入
    • @KaushikShrestha 查看我的更新答案
    • 感谢您的努力,但我没有使用 mysql db 和 php,而是使用 Postgres 和 hibernate 框架(在 java 中)
    • @KaushikShrestha 检查我的更新答案
    • 使用max(id) 是一个非常的坏主意。在多个并发事务的情况下,它将为您提供正确的结果。 唯一正确的方法是使用curval()returning子句。
    【解决方案3】:

    使用 SELECT CURRVAL(); .通常与 pg_get_serial_sequence 结合使用

    postgreSQL function for last inserted ID

    【讨论】:

    • 这仅在您一次只插入一行时才有用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-15
    • 1970-01-01
    • 2010-09-19
    • 2014-01-11
    • 1970-01-01
    • 2023-03-29
    • 2011-04-06
    相关资源
    最近更新 更多