简体   繁体   English

如何在Rails Rake任务中将参数传递给mysql查询?

[英]How do you pass a parameter to mysql query in a rails rake task?

I am changing the encoding of all my tables from latin1 to utf8mb4 using a rails rake task. 我正在使用rails rake任务将所有表的编码从latin1更改为utf8mb4

I want to: 我想要:

  1. Grab all the tables where the encoding is NOT utf8mb4 抓取所有编码不是utf8mb4的表
  2. Change the character set for each of those tables. 更改每个表的字符集。

I can grab all the tables that have the wrong enconding with 我可以抓住所有错误的表

results = ActiveRecord::Base.connection.execute <<-STRING
   SHOW TABLE STATUS WHERE collation <> 'utf8mb4'
STRING

I'm stuck with how to pass the table name for each of those tables to the mysql query so that the table encoding can be altered. 我对如何将每个table name传递给mysql查询感到困惑,以便可以更改表编码。

results.each do |table|
  ActiveRecord::Base.connection.execute <<-STRING
  ALTER TABLE #{table.table_name} CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_bin
  STRING
end

Each result is an array: 每个结果都是一个数组:

results.first.class
 => Array

And the first value returned by SHOW TABLE STATUS is the table name. SHOW TABLE STATUS返回的第一个值是表名。 So you should be able to use something like: 因此,您应该可以使用类似:

results.each do |table|
  ActiveRecord::Base.connection.execute <<-STRING
  ALTER TABLE #{table[0]} CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_bin
  STRING
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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