Wednesday, December 2, 2009

How to execute SQL Query in rails Application



connection = ActiveRecord::Base.connection();

Example :
1. connection.execute(any_sql_query)

2.
results = connection.execute("select * from users")
results.each do |row|
puts row[0]
end

5 comments:

  1. Abdul,

    I'm just getting my feet wet in RoR for MySQL with mysql gem. Is it possible to work, locally with your intended schema (varchar(2) for instance, instead of string)?

    If so, how do we preserve a schema from the xxxxDateTimeStamped_tablename.rb throughout table creation, migration, development, testing, and deployment?

    Is it possible to do something like this for instance:


    class CreateAmendments < ActiveRecord::Migration
    def self.up
    create_table :amendments do |t|
    connection = ActiveRecord::Base.connection()
    connection.execute(CREATE TABLE amendments (id integer NOT NULL AUTO_INCREMENT PRIMARY KEY, c_code varchar(2), c_name varchar(35), tran_id integer), priority tinyint, created_at datetime, updated_at datetime) ENGINE=InnoDB;)
    end
    end

    If so, do we ourselves declare the usual id and timestamps (date_created, date_modified) fields which are automated by scaffolding?

    TIA

    mike

    ReplyDelete
  2. Call off the dogs, Abdul. Execute "[SQLStatement]" works great, if you haven't tried it.

    ReplyDelete
  3. create_table :amendments do |t|
    end

    will create your table, so why you are trying to create table amendments in the block again??

    If you create table manually(except migration) then you have to declare id(primary key with AUTO increment) and timestamps(created_at, updated_at) for that table and Rails will invoke id and timestamps automatically

    btw, thanks for your reply,keep in mind "convention over configuration for ROR". If your convention is OK than Rails will OK.

    ReplyDelete
  4. I used code given below in rails 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

    but getting error:-

    `': undefined method `execute' for # (NoMethodError)

    ReplyDelete
  5. Hello neeraj, You are using ActiveRecord::Base.establish_connection which is type of ActiveRecord::ConnectionAdapters::ConnectionPool and it has no execute method thats why you are getting NoMethod Error


    Use ActiveRecord::Base.connection() of typed ActiveRecord::ConnectionAdapters::Mysql2Adapter which has execute method.

    Anyway thanks for your comments :-)

    ReplyDelete