如果使用ruby,另一个解决方案是使用ActiveRecord将连接脚本写入数据库。你需要先安装它
gem install activerecord# ruby ./export-mysql.rb
require 'rubygems'
require 'active_record'
ActiveRecord::Base.establish_connection(
:adapter =>"mysql",
:database =>"database_name",
:username =>"root",
:password =>"",
:host =>"localhost"
)
class Event < ActiveRecord::Base; end
class Person < ActiveRecord::Base; end
File.open("events.json","w") { |f| f.write Event.all.to_json }
File.open("people.json","w") { |f| f.write Person.all.to_json }
如果要首先操作数据或包含或排除某些列,也可以向ActiveRecord类中添加方法。Person.all.to_json(:only => [ :id, :name ])
使用ActiveRecord,你不限于JSON。你可以轻松地导出为XML或YAMLPerson.all.to_xml
Person.all.to_yaml
你不限于MySQL,ActiveRecord支持的任何数据库(Postgres,SQLite3,Oracle ...等)。
值得一提的是,你可以打开另一个数据库句柄,require 'active_record'
ActiveRecord::Base.configurations["mysql"] = {
:adapter => 'mysql',
:database => 'database_name',
:username => 'root',
:password => '',
:host => 'localhost'
}
ActiveRecord::Base.configurations["sqlite3"] = {
:adapter => 'sqlite3',
:database => 'db/development.sqlite3'
}
class PersonMySQL < ActiveRecord::Base
establish_connection"mysql"
end
class PersonSQLite < ActiveRecord::Base
establish_connection"sqlite3"
end
PersonMySQL.all.each do |person|
PersonSQLite.create(person.attributes.except("id"))
end