Mysql / Ruby Continue last insert id value, which method?

I just want to get last_insert_id () using Ruby 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 

A SELECT query should return last_id, but .run does not return it. Which method should be used instead?

Solution: (thanks to Josh Lindsay)

 last_insert_id = @con[:wv_persons].insert({}) last_insert_id = last_insert_id.to_s puts "New person ["+ last_insert_id +"]" 
+4
source share
3 answers

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

 DB[:wv_persons].insert({}) 

Paste the default values ​​and return the identifier.

Database # run will always return nil .

+7
source

Actually, Database # insert is not guaranteed to return the identifier of the last inserted record.

From the documentation: "... Inserts values ​​into a linked table. The return value is usually the primary key value for the inserted row, but it depends . "

+5
source

The continuation of gem should return the identifier of the newly inserted records , but as others have said:

  • return value depends on adapter

Also I would like to add ...

  • not sure what to return when encountering a composite primary key

You can get around this by specifying a continuation that 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}]

0
source

All Articles