Reputation: 3588
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 +"]"
Upvotes: 6
Views: 4222
Reputation: 7781
The sequel gem is supposed to return the id of newly inserted records but as others said:
also i'd like to add...
You can get around this by telling sequel exactly what should be returned using the #returning
method.
For instance:
DB[:posts].returning(:id).insert(category_id: 5, id: 1, ...)
will return [{id: 1}]
and
DB[:posts].returning(:id, :category_id).insert(category_id: 5, id: 1, ...)
will return [{id: 1, category_id: 5}]
Upvotes: 1
Reputation: 51
Actually, Database#insert is not guaranteed to return the id of the last inserted record.
From the documentation: "...Inserts values into the associated table. The returned value is generally the value of the primary key for the inserted row, but that is adapter dependent."
Upvotes: 5
Reputation: 8803
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
.
Upvotes: 9