开发者

Last inserted row id in PostgreSQL

开发者 https://www.devze.com 2023-03-04 03:10 出处:网络
I am using postgresql database. And previous tables which are created by my seniors and they are not used sequence concept, they added data manually. Now i need to insert data with my java application

I am using postgresql database. And previous tables which are created by my seniors and they are not used sequence concept, they added data manually. Now i need to insert data with my java application. for that i need last inserted ID. I have no permission to add sequence开发者_如何转开发.

please anybody help me.

thanks in advance...


You'd ideally ask for permission to create the needed sequences.

If it's not an option for some bureaucratic reason you might manage to work around concurrency issues using advisory locks. Pseudo-code:

loop
select id as last_id, pg_try_advisory_lock('yourtable'::regclass, id) as locked
from yourtable
order by id desc limit 1

 if not locked then sleep .01 else exit end if
end loop

new_id = last_id + 1
insert...

select pg_advisory_unlock('yourtable'::regclass, last_id)
0

精彩评论

暂无评论...
验证码 换一张
取 消