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
4

5 回答 5

168

也许试试这个:

ActiveRecord::Base.establish_connection(...)
ActiveRecord::Base.connection.execute(...)
于 2013-03-14T11:48:56.277 回答
100
connection = ActiveRecord::Base.connection
connection.execute("SQL query") 
于 2013-03-14T11:52:36.637 回答
38

我建议使用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

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

于 2016-05-24T02:09:40.207 回答
25

你也可以使用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"}>, ...]
于 2013-10-24T12:43:13.197 回答
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

于 2013-03-14T11:45:40.200 回答