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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15408285/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 14:15:17  来源:igfitidea点击:

Rails 3 execute custom sql query without a model

sqlruby-on-rails

提问by neeraj

I need to write a standalone ruby script that is supposed to deal with database. I used code given below in rails 3

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

but getting error:-

但出现错误:-

`<main>': undefined method `execute' for #<ActiveRecord::ConnectionAdapters::ConnectionPool:0x00000002867548> (NoMethodError)

what i am missing here?

我在这里缺少什么?

SOLUTION

解决方案

After getting solution from denis-bu i used it following way and that worked too.

从 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

回答by denis-bu

Maybe try this:

也许试试这个:

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

回答by Sachin R

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

回答by hajpoj

I'd recommend using ActiveRecord::Base.connection.exec_queryinstead of ActiveRecord::Base.connection.executewhich returns a ActiveRecord::Result(available in rails 3.1+) which is a bit easier to work with.

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

Then you can access it in various the result in various ways like .rows, .each, or .to_hash

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

From the 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

note: copied my answer from here

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

回答by montrealmike

You could also use find_by_sql

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

回答by ant

How about this :

这个怎么样 :

@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

You need to have TinyTds gem installed, since you didn't specify it in your question I didn't use Active Record

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