public
Created

Inserting multiple rows at once into SQLite3 using raw SQL

  • Download Gist
sqlinsert.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
# values_to_insert is an array of type
# [
# [val1.1, val1.2]
# [val2.1, val2.2],
# [val3.1, val3.2],
# ...etc
# ]
 
sql = ActiveRecord::Base.connection
 
# breaking up into chunks of 499.
require 'enumerator'
values_to_insert.each_slice(499) do |chunk|
sqlcommand = "INSERT INTO tablename (value1, value2) SELECT #{chunk[0][0]} AS value1, #{chunk[0][1]} AS value2"
chunk[1..-1].each do |value_pair|
sqlcommand += " UNION SELECT '#{value_pair[0]}','#{value_pair[1]}'"
end
sql.execute(sqlcommand)
end

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.