我需要编写一个独立的 Ruby 脚本来处理数据库。我使用了 Rails 3中给出的代码
@connection = ActiveRecord::Base.establish_connection(
:adapter => "mysql2",
:host => "localhost",
:database => "siteconfig_development",
:username => "root",
:password => "root123"
)
results = @connection.execute("select * from users")
results.each do |row|
puts row[0]
end
但是出现了错误:-
`<main>': undefined method `execute' for #<ActiveRecord::ConnectionAdapters::ConnectionPool:0x00000002867548> (NoMethodError)
我错过了什么?
解决方案
从丹尼斯-布那里得到溶液后,我按照下面的方法使用它,也起作用了。
@connection = ActiveRecord::Base.establish_connection(
:adapter => "mysql2",
:host => "localhost",
:database => "siteconfig_development",
:username => "root",
:password => "root123"
)
sql = "SELECT * from users"
@result = @connection.connection.execute(sql);
@result.each(:as => :hash) do |row|
puts row["email"]
end