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


105

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

Answers:



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

8
在这种情况下,connection = ActiveRecord :: Base.connection; connection.execute(“ SQL查询”)将起作用。少打字!
Watusimoto

16
或者只是ActiveRecord::Base.connection.execute("SQL query")
Kasper Grubbe 2014年

3
之后可能必须将此连接返回到连接池,以避免出现线程问题:ActiveRecord::Base.connection_pool.checkin(connection) apidock.com/rails/ActiveRecord/ConnectionAdapters/…–
lee

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

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


1
如前所述,exec_query返回实际结果-我想要的,而execute仅返回状态信息。
Paul Chernoch

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"}>, ...]

我的脚本是在Rails应用程序外部,所以我认为find_by_sql不起作用。
neeraj 2013年

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。


1
当然,TinyTds完全是其他宝石。它不是ActiveRecord。要使用它,您应该单独安装。
denis-bu

1
只要mysql2和active-record可用,我就不想使用任何其他GEM
neeraj 2013年

好,您应该在问题(标记/标题)中提及
ant

2
TinyTDS适用于MSSQL和Sybase,不适用于MySQL。ant:应该在回答中提到这一点,而不是假设OP使用的是相同的利基DBMS。
1515年
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.