Skip to content

Instantly share code, notes, and snippets.

@minikomi
Created October 12, 2011 08:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save minikomi/1280572 to your computer and use it in GitHub Desktop.
Save minikomi/1280572 to your computer and use it in GitHub Desktop.
Inserting multiple rows at once into SQLite3 using raw SQL
# 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment