Postgres pq - LastInsertId

2,372 views
Skip to first unread message

zeroc8

unread,
May 8, 2012, 1:18:22 AM5/8/12
to golan...@googlegroups.com
Has anyone been successful getting the LastInsertId after an insert statement?

When I try to read LastInsertId() from result, I get
"pq: this is postgres, a real database, this isn't a valid command".

Fair enough, but Postgres has something like this
insert into foo values('bla') return id

Is there any way to retrieve that value?





Alexander Neumann

unread,
May 8, 2012, 5:19:13 AM5/8/12
to golang-nuts
Try something like this (untested):

err := db.QueryRow("INSERT INTO foo (bar) VALUES ($1) RETURNING id;",
bar).Scan(&id)

zeroc8

unread,
May 8, 2012, 2:03:29 PM5/8/12
to golan...@googlegroups.com


Am Dienstag, 8. Mai 2012 11:19:13 UTC+2 schrieb Alexander Neumann:
Try something like this (untested):

err := db.QueryRow("INSERT INTO foo (bar) VALUES ($1) RETURNING id;",
bar).Scan(&id)


Thanks, works.
err := tx.QueryRow("insert into car(name) values($1) returning id","test").Scan(&id)
   
 

zeroc8

unread,
May 8, 2012, 2:04:15 PM5/8/12
to golan...@googlegroups.com

Justin Wilson

unread,
Jul 9, 2013, 7:04:25 PM7/9/13
to golan...@googlegroups.com
Just what I was looking for too, thanks =)

Arne Hormann

unread,
Jul 10, 2013, 4:26:21 AM7/10/13
to golan...@googlegroups.com
I never used the pg driver, but why don't you use Exec instead of Query? Exec returns sql.Result, which has a method LastInsertId().

notedit

unread,
Jul 10, 2013, 4:51:04 AM7/10/13
to Arne Hormann, golang-nuts
the pg driver's  sql.Result does not return lastinsertid.

err := db.QueryRow("INSERT INTO foo (bar) VALUES ($1) RETURNING id;",
bar).Scan(&id)

this will have another question, if the insert has some error, it will return some like "no result error".


2013/7/10 Arne Hormann <arneh...@gmail.com>
I never used the pg driver, but why don't you use Exec instead of Query? Exec returns sql.Result, which has a method LastInsertId().

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.
 
 

Kamil Kisiel

unread,
Jul 10, 2013, 12:12:06 PM7/10/13
to golan...@googlegroups.com
Postgres by default does not return the last inserted id unless you explicitly ask for it with the RETURNING clause. However the fields returned by the clause can be arbitrarily specified, so there's no way to identify a single id without knowledge of the schema and query.

Reply all
Reply to author
Forward
0 new messages