我需要创建一个rake任务,从MySQL数据库获取表行,解析数据并插入Oracle数据库。数据库位于两个不同的主机上。
我目前的尝试:
namespace :import_from_mysql do
class MySQLConnection < ActiveRecord::Base
self.abstract_class = true
establish_connection({
:adapter => 'mysql',
:host => 'xxx.xxx.com',
:database => 'sample_database',
:username => 'username',
:password => 'password'
})
end
class MySQLTable < MySQLConnection
self.table_name = "users"
self.primary_key = "id"
self.inheritance_column = "something_unique_here"
end
desc "Parse data before inserting to oracle database"
task :insert_to_oracle => :environment do |t|
puts "Rake task has begun...\n\n"
puts "Parsing data from MYSQL...\n\n"
MySQLTable.establish_connection
puts "Rake task has completed!"
end
end
但 MySQLTable.establish_connection 建立了与本地数据库的连接,即使我正在尝试连接到mysql_adapter,也是sqlite。
当我尝试使用以下命令建立连接时,我能够连接到MySQL适配器,但我不知道在建立连接后如何访问我的表:
ActiveRecord::Base.establish_connection({:adapter => "mysql", :database => "sample_database", :host => "xxx.xxx.com", :username => "username", :password => "password" })
有关为何继续连接到sqlite的任何想法?在成功建立与mysql的连接后,如何在MySQLTable.establish_connection语句之后选择表行?
答案 0 :(得分:1)
使用ActiveRecord :: Base生成连接,您可以针对连接的任何数据库执行SQL语句。像这样:
connection = ActiveRecord::Base.establish_connection(
:adapter => "mysql",
:host => "faraway",
:username => "myuser",
:password => "mypass",
:database => "somedatabase"
)
connection.execute('SELECT * FROM users')
建立后,也可以从ActiveRecord :: Base类引用连接。
ActiveRecord::Base.establish_connection(...)
ActiveRecord::Base.connection.execute(...)
答案 1 :(得分:1)
虽然我是一个连接和“数据库后台办公室”的菜鸟,但我的琐碎方法就像一个魅力,并且rake任务中不需要参数来更新仅包含定义数据的“域表”,例如合法或帮助文本:
pre_db = ActiveRecord::Base.establish_connection('preproduction').connection
prod_db = ActiveRecord::Base.establish_connection('online').connection
并在database.yml
我定义了数据库。 (“前期制作”是我个案中dev和prod之间的一个步骤,以及像“开发”这样的真实环境。其中'online'几乎与'production'相同(我出于安全原因做了一个不同的条目 - 不破坏生产如果上传database.yml
答案 2 :(得分:0)
您可以在rake任务中使用mysql2 gem(https://github.com/brianmario/mysql2)。
client = Mysql2::Client.new(:host => "localhost", :username => "username", :database => "sample_database", :password => "password")
users = client.query("SELECT * FROM users")
答案 3 :(得分:0)
认为它可能对其他人有帮助。以下对我有用!
connection = ActiveRecord::Base.establish_connection(
:adapter => "mysql",
:host => "faraway",
:username => "myuser",
:password => "mypass",
:database => "somedatabase"
)
@connection = ActiveRecord::Base.connection
result = @connection.exec_query('SELECT * FROM users')
result.each do |row|
puts row
end
此处,用户是“somedatabase”中已存在的表。