Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get last inserted id using mysql2 gem

Tags:

mysql

ruby


I have code like this:

   require 'mysql2' 
   @db.query("insert into clients (Name) values ('#{client}')") 

Can I return last inserted id with 1 query?

like image 956
babi4 Avatar asked Aug 26 '11 07:08

babi4


2 Answers

You can use last_id method of the client instance:

client = Mysql2::Client.new(:host => "localhost", :username => "root", :password => "", :database => "db")
insert = client.query "INSERT INTO test (name, date) VALUES ('name', '2011-11-28 09:13:56')"
id = client.last_id

http://rubydoc.info/gems/mysql2/0.2.6/Mysql2/Client:last_id

Edit: it doesn't answer your original question but still looks better than call for LAST_INSERT_ID

like image 113
Ilya Tsuryev Avatar answered Oct 01 '22 10:10

Ilya Tsuryev


I don't anything about gem but you can try to run

@db.query("SELECT LAST_INSERT_ID();") 

after your first query.

like image 38
Andrej Ludinovskov Avatar answered Oct 01 '22 09:10

Andrej Ludinovskov