Rails 3在没有模型的情况下执行自定义的sql查询

我需要编写一个独立的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) 

我在这里错过了什么?

从denis-bu获得解决scheme后,我用下面的方式,也工作。

 @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 

也许试试这个:

 ActiveRecord::Base.establish_connection(...) ActiveRecord::Base.connection.execute(...) 
 connection = ActiveRecord::Base.connection connection.execute("SQL query") 

我build议使用ActiveRecord::Base.connection.exec_query而不是ActiveRecord::Base.connection.execute ,它返回一个ActiveRecord::Result (在rails 3.1+中可用),这有点容易处理。

然后,您可以通过各种方式(如.rows.each.to_hash以各种方式访问​​它

从文档 :

 result = ActiveRecord::Base.connection.exec_query('SELECT id, title, body FROM posts') result # => #<ActiveRecord::Result:0xdeadbeef> # Get the column names of the result: result.columns # => ["id", "title", "body"] # Get the record values of the result: result.rows # => [[1, "title_1", "body_1"], [2, "title_2", "body_2"], ... ] # Get an array of hashes representing the result (column => value): result.to_hash # => [{"id" => 1, "title" => "title_1", "body" => "body_1"}, {"id" => 2, "title" => "title_2", "body" => "body_2"}, ... ] # ActiveRecord::Result also includes Enumerable. result.each do |row| puts row['title'] + " " + row['body'] end 

注意:从这里复制我的答案

你也可以使用find_by_sql

 # A simple SQL query spanning multiple tables Post.find_by_sql "SELECT p.title, c.author FROM posts p, comments c WHERE p.id = c.post_id" > [#<Post:0x36bff9c @attributes={"title"=>"Ruby Meetup", "first_name"=>"Quentin"}>, ...] 

这个怎么样 :

 @client = TinyTds::Client.new( :adapter => 'mysql2', :host => 'host', :database => 'siteconfig_development', :username => 'username', :password => 'password' sql = "SELECT * FROM users" result = @client.execute(sql) results.each do |row| puts row[0] end 

你需要安装TinyTds gem,因为你没有在你的问题中指定它,我没有使用Active Record