nee*_*raj 104 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
Run Code Online (Sandbox Code Playgroud)
但得到错误: -
`<main>': undefined method `execute' for #<ActiveRecord::ConnectionAdapters::ConnectionPool:0x00000002867548> (NoMethodError)
Run Code Online (Sandbox Code Playgroud)
我在这里失踪了什么?
解
从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
Run Code Online (Sandbox Code Playgroud)
den*_*-bu 167
也许试试这个:
ActiveRecord::Base.establish_connection(...)
ActiveRecord::Base.connection.execute(...)
Run Code Online (Sandbox Code Playgroud)
Sac*_*n R 100
connection = ActiveRecord::Base.connection
connection.execute("SQL query")
Run Code Online (Sandbox Code Playgroud)
haj*_*poj 35
我建议使用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
Run Code Online (Sandbox Code Playgroud)
注意:从这里复制我的答案
mon*_*ike 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"}>, ...]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
125096 次 |
| 最近记录: |