简体   繁体   中英

Using prepared statement in Rails to insert multiple rows

I am currently working on RoR with PostgreSQL.

Basically, ActiveRecord satisfies most of the requirement of data retrieval. However, in some cases, it seems that using one statement would be much more efficient.

Therefore, is it possible to use one prepared statement to do multiple insert as the followings? Or I have to append the raw sql statement myself?

INSERT INTO films (code, title, did, date_prod, kind) VALUES
    ('B6717', 'Tampopo', 110, '1985-02-10', 'Comedy'),
    ('HG120', 'The Dinner Game', 140, DEFAULT, 'Comedy'), ...;

try this

user_string = " ('code1','title1', 'aaa', ...), ('code2','title2'...)"

User.connection.insert("INSERT INTO films (code, title, did, date_prod, kind)VALUES"+user_string) 

After two years of experience working on RoR,

There is a gem called activerecord-import that can do the thing. And here is the example code.

books = Array.new
books << Book.new(title: "Programming Ruby", author: "Dave Thomas")
books << Book.new(title: "Agile Web Development with Rails 5", author: "Sam Ruby")
Book.import books

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM