且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用 ruby​​ on rails 活动记录插入多条记录

更新时间:2023-01-27 12:40:28

create 方法也接受一个数组作为参数.

The create method takes also an array as parameter.

VoteRecord.create(
  [
    { :prospect_id => prospect.id, :state => "OH", :election_type => "GE", :election => "2011-11-08", :party => row[82], :participate => participated(row[82]) },
    { :prospect_id => prospect.id, :state => "OH", :election_type => "PR", :election => "2011-09-13", :party => row[81], :participate => participated(row[81]) }
    ...
  ]
)

然而,这仍然为每个条目执行一个 SQL 查询,而不是单个 SQL 查询.它更有效,因为它只需要在后台创建一个单独的 activerecord 对象.

However, this still executes one SQL query per entry instead of a single SQL query. It is more efficent, because it only has to create a single activerecord object under the hood.

如果您同时插入来自同一个客户端的多行,使用带有多个 VALUES 列表的 INSERT 语句插入多个一次行.这要快得多(在某些情况下要快很多倍)案例)而不是使用单独的单行 INSERT 语句.如果你是将数据添加到非空表,您可以调整bulk_insert_buffer_size 变量使数据插入更快.请参阅第 5.1.3 节,服务器系统变量".

If you are inserting many rows from the same client at the same time, use INSERT statements with multiple VALUES lists to insert several rows at a time. This is considerably faster (many times faster in some cases) than using separate single-row INSERT statements. If you are adding data to a nonempty table, you can tune the bulk_insert_buffer_size variable to make data insertion even faster. See Section 5.1.3, "Server System Variables".

来自 mysql 页面(但我猜其他dbs应该是一样的)

From the mysql page (but I guess it should be the same for other dbs)