Pretty straight forward problem. I simply want to return the affected row created by a SQL INSERT query so I can get data from it.
There’s a way I can do it already, I suppose, but I’m hoping the Mysql or Mysql2 gem provides some mechanism for me not having to make the second SELECT query.
The solution I’m leaning towards right now is something akin to:
"INSERT INTO table (col1) VALUES ('value');"
and then:
"SELECT cid FROM table ORDER BY cid DESC LIMIT 1;"
Since cid is the auto-increment index of the table (it’s InnoDB fyi), it will always be the largest cid value in the table until you do another INSERT.
Is there any mechanism in Mysql or Mysql2 to avoid having to make that second SELECT query?
MySQL2 has a
last_idmethod. The documentation for that method is worthless but the implementation looks like this:And the MySQL
mysql_insert_idfunction does this:So you can do your INSERT and then get the last ID by calling the
last_idmethod.And BTW, your current approach:
is not safe if you’re in a multiprocess environment, consider this:
SELECT cid FROM table ORDER BY cid DESC LIMIT 1and get the ID from (2).You could
SELECT last_insert_id()though,last_insert_id()is session-specific so you don’t have to worry about other processes when using it.