How do you manually execute SQL commands in Ruby On Rails using NuoDB

前端 未结 4 1791
醉梦人生
醉梦人生 2020-12-22 19:38

I\'m trying to manually execute SQL commands so I can access procedures in NuoDB.

I\'m using Ruby on Rails and I\'m using the following command:

Acti         


        
相关标签:
4条回答
  • 2020-12-22 20:03
    res = ActiveRecord::Base.connection_pool.with_connection { |con| con.exec_query( "SELECT 1;" ) }
    

    The above code is an example for

    1. executing arbitrary SQL on your database-connection
    2. returning the connection back to the connection pool afterwards
    0 讨论(0)
  • 2020-12-22 20:04

    For me, I couldn't get this to return a hash.

    results = ActiveRecord::Base.connection.execute(sql)
    

    But using the exec_query method worked.

    results = ActiveRecord::Base.connection.exec_query(sql)
    
    0 讨论(0)
  • 2020-12-22 20:12

    Reposting the answer from our forum to help others with a similar issue:

    @connection = ActiveRecord::Base.connection
    result = @connection.exec_query('select tablename from system.tables')
    result.each do |row|
    puts row
    end
    
    0 讨论(0)
  • 2020-12-22 20:25

    The working command I'm using to execute custom SQL statements is:

    results = ActiveRecord::Base.connection.execute("foo")
    

    with "foo" being the sql statement( i.e. "SELECT * FROM table").

    This command will return a set of values as a hash and put them into the results variable.

    So on my rails application_controller.rb I added this:

    def execute_statement(sql)
      results = ActiveRecord::Base.connection.execute(sql)
    
      if results.present?
        return results
      else
        return nil
      end
    end
    

    Using execute_statement will return the records found and if there is none, it will return nil.

    This way I can just call it anywhere on the rails application like for example:

    records = execute_statement("select * from table")
    

    "execute_statement" can also call NuoDB procedures, functions, and also Database Views.

    0 讨论(0)
提交回复
热议问题