복붙노트

[RUBY-ON-RAILS] 3 모델없이 사용자 정의 SQL 쿼리를 실행 레일

RUBY-ON-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)

내가 여기서 무엇을 놓치고?

해결책

데니스-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

해결법

  1. ==============================

    1.어쩌면이 시도 :

    어쩌면이 시도 :

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

    2.

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

    3.내가 대신 액티브의 액티브 :: Base.connection.exec_query :: Base.connection.execute (3.1 레일시) 액티브 :: 결과를 반환과 함께 작업을 조금 더 쉽게 사용하는 것이 좋습니다 것입니다.

    내가 대신 액티브의 액티브 :: Base.connection.exec_query :: Base.connection.execute (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
    

    참고 : 여기에서 내 대답을 복사

  4. ==============================

    4.또한 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"}>, ...]
    
  5. ==============================

    5.이건 어때 :

    이건 어때 :

    @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 보석이 설치되어 있어야합니다

  6. from https://stackoverflow.com/questions/15408285/rails-3-execute-custom-sql-query-without-a-model by cc-by-sa and MIT license