如何在插入行后立即获取序列号? [英] How to get the serial id just after inserting a row?

查看:174
本文介绍了如何在插入行后立即获取序列号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

无需在id中添加任何值,因为它默认设置为serial。



如何检索刚才插入的行的id?

解决方案

因为它是连续的,所以可以使用从tableName中选择max(id)

 使用max(id)是一个非常糟糕的主意。在多个并发事务的情况下,它不会给你正确的结果
。唯一正确的方法是使用
curval()或返回子句。

posgresql :已经有一个<一个href =https://stackoverflow.com/questions/3687698/select-display-last-inserted-serial-id-in-postgres> 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用户:



From php.net 点击

 <?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(最后插入的记录有id%d \ n,mysqli :: $ insert_id());
?>

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


I have a table with row 'id' (a primary key) default set to serial in PostgreSQL. I insert into this row by calling

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

without adding any value into id as it is default set to serial.

How can I retrieve the `id' of just inserted row?

解决方案

Since it is serial you can use 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.

In posgresql: There is already a stackoverflow-question exists BTW.

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

(also)

Get a specific sequence:

SELECT currval('name_of_your_sequence');

Get the last value from the last sequence used:

SELECT lastval();

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

For PHP-mysql users:

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

But you need to connect for every query.

这篇关于如何在插入行后立即获取序列号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆