Mysql/Ruby Sequel最后插入ID值,有什么方法?

ost*_*oon 4 ruby mysql sequel

我只想使用Ruby的续集获取last_insert_id():

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
Run Code Online (Sandbox Code Playgroud)

SELECT查询应返回last_id,但.run不返回它.我应该用什么方法代替?

解决方案:(感谢Josh Lindsey)

last_insert_id = @con[:wv_persons].insert({})
last_insert_id = last_insert_id.to_s
puts "New person ["+ last_insert_id  +"]"
Run Code Online (Sandbox Code Playgroud)

Jos*_*sey 7

数据集#插入方法应返回最后一个插入ID:

DB[:wv_persons].insert({})
Run Code Online (Sandbox Code Playgroud)

将插入默认值并返回id.

Database#run将始终返回nil.


小智 5

实际上,不保证Database#insert返回最后插入记录的id.

从文档中:"...将值插入到关联的表中.返回的值通常是插入行的主键值,但这取决于适配器. "