Programing

Rails 3는 모델없이 커스텀 SQL 쿼리를 실행합니다.

lottogame 2020. 8. 12. 22:10
반응형

Rails 3는 모델없이 커스텀 SQL 쿼리를 실행합니다.


데이터베이스를 처리해야하는 독립 실행 형 루비 스크립트를 작성해야합니다. 레일 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

어쩌면 이것을 시도하십시오 :

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

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

ActiveRecord::Base.connection.exec_query대신 작업하기가 더 쉬운 (레일 3.1 이상에서 사용 가능) ActiveRecord::Base.connection.execute을 반환하는 대신 사용 하는 것이 좋습니다 ActiveRecord::Result.

다음과 같은 다양한 방법으로 다양한에 결과를 액세스 할 수 있습니다 .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

참고 : 여기 에서 내 대답을 복사했습니다 .


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

이건 어때요 :

@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

참고URL : https://stackoverflow.com/questions/15408285/rails-3-execute-custom-sql-query-without-a-model

반응형