ActiveRecord::Base.connection.execute 的受影响行

Affected rows for ActiveRecord::Base.connection.execute(ActiveRecord::Base.connection.execute 的受影响行)
本文介绍了ActiveRecord::Base.connection.execute 的受影响行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 Rails 4.1.1,使用 mysql2 适配器:

With Rails 4.1.1, using mysql2 adapter:

我正在使用 ActiveRecord connection 来执行MySQL 表中的多次插入:

I am using an ActiveRecord connection to execute a multiple insert in a MySQL table:

ActiveRecord::Base.connection.execute %Q{
    INSERT INTO table (`user_id`, `item_id`) 
    SELECT 1, id FROM items WHERE items.condition IS NOT NULL
}

这工作正常,完成工作,并返回 nil.

This works fine, do the job, and returns nil.

有没有办法获取受影响的行数?(避免需要执行另一个查询)

Is there a way to get the number of affected rows? (avoiding the need to execute another query)

我找到了 的文档execute 方法有点稀疏.

I have found the documentation of the execute method somewhat sparse.

推荐答案

您可以使用 connection.update 方法执行表达式并返回受影响的行数.

You can use connection.update method which executes expression and returns affected rows count.

ActiveRecord::Base.connection
  .update("INSERT INTO accounts (`name`) VALUES ('first'), ('second')")

=> 2

Rails v4.2.7 文档 - http://api.rubyonrails.org/v4.2.7/classes/ActiveRecord/ConnectionAdapters/DatabaseStatements.html#method-i-update

Rails v4.2.7 doc - http://api.rubyonrails.org/v4.2.7/classes/ActiveRecord/ConnectionAdapters/DatabaseStatements.html#method-i-update

Rails 最新文档 - http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/DatabaseStatements.html#method-i-update

Rails latest doc - http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/DatabaseStatements.html#method-i-update

这篇关于ActiveRecord::Base.connection.execute 的受影响行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Hibernate reactive No Vert.x context active in aws rds(AWS RDS中的休眠反应性非Vert.x上下文处于活动状态)
Bulk insert with mysql2 and NodeJs throws 500(使用mysql2和NodeJS的大容量插入抛出500)
Flask + PyMySQL giving error no attribute #39;settimeout#39;(FlASK+PyMySQL给出错误,没有属性#39;setTimeout#39;)
auto_increment column for a group of rows?(一组行的AUTO_INCREMENT列?)
Sort by ID DESC(按ID代码排序)
SQL/MySQL: split a quantity value into multiple rows by date(SQL/MySQL:按日期将数量值拆分为多行)