以MySQL为例,建立数据库mydb,在其中创建表mytab,为简单起见,该表只设两个字段:
创建Ruby源程序mydb.rb:
['10', 'I was inserted by ActiveRecord.']
create table mytab
{
id int not null,
msg varchar(100)
}
{
id int not null,
msg varchar(100)
}
创建Ruby源程序mydb.rb:
require 'rubygems'
require_gem 'activerecord' # 请注意使用rubygems时候的声明方式
# 连接数据库,按需求填写各种参数。
ActiveRecord::Base.establish_connection(:adapter => "mysql",
:host => "localhost", :database => "mydb")
class Mytab < ActiveRecord::Base # 开始ORM对应
set_table_name 'mytab' # 指定数据库名
end
# 插入一条数据
tab = Mytab.new
tab.id=10
tab.msg = 'I was inserted by ActiveRecord.'
tab.save
# 显示所有数据
data = Mytab.find(:all)
data.each { |line| puts "['#{line[:id]}', '#{line[:msg]}']" }
运行结果:require_gem 'activerecord' # 请注意使用rubygems时候的声明方式
# 连接数据库,按需求填写各种参数。
ActiveRecord::Base.establish_connection(:adapter => "mysql",
:host => "localhost", :database => "mydb")
class Mytab < ActiveRecord::Base # 开始ORM对应
set_table_name 'mytab' # 指定数据库名
end
# 插入一条数据
tab = Mytab.new
tab.id=10
tab.msg = 'I was inserted by ActiveRecord.'
tab.save
# 显示所有数据
data = Mytab.find(:all)
data.each { |line| puts "['#{line[:id]}', '#{line[:msg]}']" }
['10', 'I was inserted by ActiveRecord.']