Mysql/Ruby Sequel最后插入ID值,用什么方法?
我只想使用 Ruby 的 Sequel 获取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
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 +"]"
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 +"]"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Dataset#insert 方法应返回最后一个插入 id:
将插入默认值并返回 id。
Database#run 将始终返回
nil
。The Dataset#insert method should return the last insert id:
Will insert the default values and return the id.
Database#run will always return
nil
.实际上, Database#insert 不能保证返回最后插入的记录的 id。
文档中:“...将值插入关联表中。返回的值通常是插入行的主键值,但这依赖于适配器。”
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."
续集 gem 应该返回新插入记录的 id 但正如其他人所说:
我也想添加...
您可以通过使用
#returning
方法准确告诉sequel应该返回什么来解决这个问题。例如:
DB[:posts].returning(:id).insert(category_id: 5, id: 1, ...)
将返回
[{id: 1}]
和
DB[:posts].returning(:id, :category_id).insert(category_id: 5, id: 1, ...)
将返回
[{id: 1,类别 ID: 5}]
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}]