Affected rows for 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 的受影响行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:ActiveRecord::Base.connection.execute 的受影响行
基础教程推荐
- MySQL根据从其他列分组的值,对两列之间的值进行求和 2022-01-01
- 带更新的 sqlite CTE 2022-01-01
- 从字符串 TSQL 中获取数字 2021-01-01
- CHECKSUM 和 CHECKSUM_AGG:算法是什么? 2021-01-01
- ORA-01830:日期格式图片在转换整个输入字符串之前结束/选择日期查询的总和 2021-01-01
- while 在触发器内循环以遍历 sql 中表的所有列 2022-01-01
- MySQL 5.7参照时间戳生成日期列 2022-01-01
- 带有WHERE子句的LAG()函数 2022-01-01
- 如何在 CakePHP 3 中实现 INSERT ON DUPLICATE KEY UPDATE aka upsert? 2021-01-01
- 使用 VBS 和注册表来确定安装了哪个版本和 32 位 2021-01-01
