반응형
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
반응형
'Programing' 카테고리의 다른 글
Android의 가비지 수집기 (0) | 2020.08.12 |
---|---|
plot.new () 오류 : R에서 그림 여백이 너무 큽니다. (0) | 2020.08.12 |
저장 프로 시저가 일반적으로 최신 RDBMS의 인라인 문보다 더 효율적입니까? (0) | 2020.08.12 |
Rails 및 PostgreSQL : 역할 postgres가 존재하지 않습니다. (0) | 2020.08.12 |
다차원 배열의 모든 열 값을 합하는 방법은 무엇입니까? (0) | 2020.08.12 |