JRUBY 101 COURSE I HAVE TESTED THE CODE ALL RIGHT

Using ActiveRecord and JDBC with JRuby – Part 2

Using ActiveRecord and JDBC with JRuby – Part 2

Part 2

Continuing from where we left off in Part 1 of the article – Using ActiveRecord and JDBC with JRuby, let us now create a database called students and a table called rubyists (this holds say, the names and cities of all those who have downloaded my JRuby eBook). To do this, open a command window and type:

mysql -u root

You should now get a mysql prompt. Next at the mysql prompt, type as follows:

mysql>create database students;

It will respond with:

Query OK, 1 row affected (0.00 sec)

Next, on the mysql prompt, type:

mysql>grant all on students.* to 'root'@'localhost';

Next let us create our table called rubyists by typing the following on the mysql prompt:

mysql>use students;
drop table if exists rubyists;
create table rubyists (
   id int not null auto_increment,
   name varchar(100) not null,
   city text not null,
   primary key (id)
);

We are through with the database creation. Now type:

mysql>exit

Generally speaking, managing changes to a database schema has been one of the most odious tasks for a team of developers. Most have relied on storing DDL in revision control, ever vigilant to ensure that our database creation scripts are updated and consistent with each rollout. That solution can be very clumsy in an Extreme Programming project. And because Rails encourages iterative development, it would be very easy to imagine the constant schema changes turning into nightmares. Fortunately, Migrations allows a developer to manage rollout, and rollback, of database schema changes in a controlled and consistent manner, and one that happens to feel very natural to a Rails programmer. However, Migrations is beyond the scope of this article. You can refer to these URLs for further information –
http://api.rubyonrails.org/classes/ActiveRecord/Migration.html
http://weblog.jamisbuck.org/2005/9/27/getting-started-with-activerecord-migrations
http://glu.ttono.us/articles/2005/10/27/the-joy-of-migrations

ActiveRecord assumes that every table it handles has as its primary key an integer column called id internally, ActiveRecord uses the value in this column to keep track of the data it has loaded from the database and to link between data in different tables.
Now let us start writing the program jruby01.rb

# jruby01.rb
require 'rubygems'
require 'active_record'

ActiveRecord::Base.establish_connection(
:adapter=> "jdbcmysql",
:host => "localhost",
:database=> "students",
:username => "root",
:password => ""
)

class Rubyist < ActiveRecord::Base
end

So far, in the above code we are:

  • Using the ActiveRecord library, available as the active_record gem
  • Using the ActiveRecord adapter namely jdbcmysql
  • Establishing a connection to the database students Please note if you have set a password say xyz for your database then make :password => “xyz”
  • Creating a class called Rubyist When you create a subclass of ActiveRecord::Base, you’re creating something that wraps a database table. By default, ActiveRecord assumes that the name of the table is the plural form of the name of the class.

Next we create entries in the table without writing any SQL. If you refer the ActiveRecord documentation, we can use the create method of ActiveRecord::Base (this method creates an object, and instantly saves it as a record) to do the same:

Rubyist.create(:name => 'Luc Juggery', :city => "Nashville, Tenessee")
Rubyist.create(:name => 'Sunil Kelkar', :city => "Pune, India")
Rubyist.create(:name => 'Adam Smith', :city => "San Fransisco, USA")

You can now query the table using find of ActiveRecord::Base

participant = Rubyist.find(:first) # returns the first object fetched by SELECT * FROM rubyists
puts %{#{participant.name} stays in #{participant.city}}

You will observe ActiveRecord examines the database tables themselves to find out which columns are available. This is how we were able to use accessor methods for participant.name without explicitly defining them: we defined them in the database, and ActiveRecord picked them up.
If you want to delete an item from the database, you can use the destroy (Deletes the record in the database) method of ActiveRecord::Base as shown:

Rubyist.find(:first).destroy

The complete program is:

# jruby01.rb
require 'rubygems'
require 'active_record'

ActiveRecord::Base.establish_connection(
:adapter=> "jdbcmysql",
:host => "localhost",
:database=> "students",
:username => "root",
:password => ""
)

class Rubyist < ActiveRecord::Base
end

Rubyist.create(:name => 'Mitali Talim', :city => "Nashville, Tenessee")
Rubyist.create(:name => 'Sunil Kelkar', :city => "Pune, India")
Rubyist.create(:name => 'Adam Smith', :city => "San Fransisco, USA")

participant = Rubyist.find(:first)
puts %{#{participant.name} stays in #{participant.city}}

Rubyist.find(:first).destroy

Run the program from the command prompt:

C:\jrubyprograms>jruby jruby01.rb

The output is:

Mitali Talim stays in Nashville, Tenessee

References

  1. Charles Nutter Charles is an amazing guy! He eats, drinks and dreams JRuby – always available to help you out. No wonder JRuby is going places.
  2. ActiveRecord::Base
原文地址:https://www.cnblogs.com/lexus/p/2361045.html