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

时间:2013-03-14 11:42:00

标签: sql ruby-on-rails

我需要编写一个独立的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获得解决方案之后,我按照以下方式使用它,这也很有效。

@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

5 个答案:

答案 0 :(得分:165)

也许试试这个:

ActiveRecord::Base.establish_connection(...)
ActiveRecord::Base.connection.execute(...)

答案 1 :(得分:100)

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

答案 2 :(得分:34)

我建议使用ActiveRecord::Base.connection.exec_query而不是ActiveRecord::Base.connection.execute,它会返回ActiveRecord::Result(在rails 3.1+中可用),这样更容易使用。

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

来自docs

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

注意:从here

复制了我的回答

答案 3 :(得分:24)

您也可以使用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"}>, ...]

答案 4 :(得分:4)

这个怎么样:

@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