views:

150

answers:

2

This code runs on my local RoR/Windows 7 (64-bit):

sql = ActiveRecord::Base.connection()
last_pk = sql.insert("insert into manual (name) values ('hello new value')")
puts 'last_pk=', last_pk

but always displays "0."

For various reasons I can't use ActiveRecord in this situation.

(Note: The above code runs fine on my shared host. Also Note: I had to replace mysql5\bin\libmySQL.dll with a different DLL per another answer on StackOverflow.com in order to get ANY database connection to work.)

A: 

Change your code to use insert_sql instead of insert, i.e.

last_pk = sql.insert_sql("insert into manual (name) values ('hello new value')")
puts 'last_pk=', last_pk

The insert_sql call is supposed to return the primary key. This is the code for insert_sql in mysql_adapter.rb.

def insert_sql(sql, name = nil, pk = nil, id_value = nil, sequence_name = nil)
  super sql, name
  id_value || @connection.insert_id
end
KandadaBoggu
sorry, that still didn't work. It still returns 0 each time. :(
Pete Alvin
I have tested this and it worked for me. It it possible that DB is throwing an error?
KandadaBoggu
A: 

If in doubt get it from mysql:

SELECT LAST_INSERT_ID()

will return the last id used for insertion. Be sure to lock both statements in a synchronized block if you do multithreading.

hurikhan77