Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mysql / Ruby Sequel last insert ID value, what method?

Tags:

mysql

ruby

sequel

I just want to get the last_insert_id() using Ruby's Sequel:

insertret = @con.run("INSERT INTO `wv_persons` ( `id` ) VALUES ( NULL )")
pp insertret.inspect # returns "nil", expected that..
last_insert_id = @con.run("SELECT LAST_INSERT_ID() AS last_id;")
pp last_insert_id.inspect # returns "nil", should be an ID

The SELECT query should return the last_id but .run does not return it. What method should I use instead?

Solution: (thanks to Josh Lindsey)

last_insert_id = @con[:wv_persons].insert({})
last_insert_id = last_insert_id.to_s
puts "New person ["+ last_insert_id  +"]"
like image 690
sougonde Avatar asked Aug 13 '10 14:08

sougonde


People also ask

How do I get the last inserted id in MySQL?

If you are AUTO_INCREMENT with column, then you can use last_insert_id() method. This method gets the ID of the last inserted record in MySQL.

What will be the value of Last_insert_id () for the newly created table?

With no argument, LAST_INSERT_ID() returns a 64-bit value representing the first automatically generated value successfully inserted for an AUTO_INCREMENT column as a result of the most recently executed INSERT statement.


1 Answers

The Dataset#insert method should return the last insert id:

DB[:wv_persons].insert({})

Will insert the default values and return the id.

Database#run will always return nil.

like image 138
Josh Lindsey Avatar answered Sep 29 '22 07:09

Josh Lindsey