How to execute SQL commands manually in Ruby On Rails using NuoDB

I am trying to execute SQL commands manually so that I can access procedures in NuoDB.

I am using Ruby on Rails and I am using the following command:

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

An "SQL query" can be any SQL statement.

Like, for example, I have a table called "Feedback", and when I execute the command:

 ActiveRecord::Base.connection.execute("SELECT `feedbacks`.* FROM `feedbacks`") 

This will only return a “true” response instead of sending me all the requested data.

This is the output in the Rails console:

 SQL (0.4ms) SELECT `feedbacks`.* FROM `feedbacks` => true 

I would like to use this to call stored procedures in NuoDB, but after calling the procedures this will also return a “true” answer.

In any case, can I execute SQL commands and get the requested data instead of getting a “true” response?

+86
sql activerecord ruby-on-rails-3 nuodb
Mar 31 '14 at 2:35
source share
4 answers

The working command that I use to execute custom SQL statements is:

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

with "foo" is a sql statement (that is, "SELECT * FROM table").

This command will return a set of values ​​as a hash and put them in the result variable.

So, on my application_controller.rb rails, 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 found records and, if not, return nil.

That way, I can just call it anywhere in the rails application, for example:

 records = execute_statement("select * from table") 

"execute_statement" can also call procedures, functions, and also representations of the NuoDB database.

+111
May 27 '15 at 5:40
source share

For me, I could not get this to return a hash.

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

But the exec_query method worked.

 results = ActiveRecord::Base.connection.exec_query(sql) 
+78
Mar 30 '16 at 17:31
source share

By posting an answer from our forum to help others with a similar problem:

 @connection = ActiveRecord::Base.connection result = @connection.exec_query('select tablename from system.tables') result.each do |row| puts row end 
+21
Jul 14 '14 at 15:16
source share
 res = ActiveRecord::Base.connection_pool.with_connection { |con| con.exec_query( "SELECT 1;" ) } 

The above code is an example for

  • executing arbitrary SQL in your database
  • returns the connection back to the connection pool
+14
Apr 22 '15 at
source share



All Articles