从旧的MySQL数据库迁移数据

时间:2012-01-13 23:26:32

标签: java mysql ruby-on-rails stored-procedures backup

我最近将一个Java EE Web应用程序(在MySQL数据库上运行)重写为Rails 3.1。现在的问题是新应用程序的数据库模型与旧应用程序的数据库模型不同,因为我添加,删除并重命名了一些属性。数据库表名也不同。

有没有办法迁移这些数据?我能想象的唯一方法是编写一个包含许多ALTER TABLE和CREATE TABLE语句的存储过程,以将数据库更新为新模型。

先谢谢。

解决方案

我最终在mysql存储过程中使用INSERT..SELECT语句来迁移数据。 INSERT INTO new_schema.new_table SELECT from old_schema.old_table。我现在正在考虑制作一个Rake任务来调用该程序并执行其他操作。

2 个答案:

答案 0 :(得分:1)

唯一的方法是编写一个脚本,从旧数据库获取数据并将其插入新数据库中。或者您可以通过某种方式连接到两个数据库,然后进行一些选择和插入查询,例如

 insert into new_db.table as select old_db.table.field1, ....

 insert into new_db.table (field_1, field_2) values (select old_db.table.field_1, ...)

无论如何,这是一个手动过程,如果可以通过脚本进行某种程度的自动化

答案 1 :(得分:0)

您可以使用mysql的information_schema在rails控制台中尝试使用rails和一些sql而不是Store过程

sql = ActiveRecord::Base.connection()
old_tables = sql.execute "select table_name from information_schema.tables where table_schema = your_old_schema"
res.each do | old_table|
  old_fields = sql.execute "select distinct column_name, data_type from information_schema.columns where table_name='#{old_table}' and table_schema='your_old_schema'"
  new_fields = sql.execute "select distinct column_name, data_type from information_schema.columns where table_name='#{old_table}' and table_schema='your_new_schema'"
  #compare fields and so on...
end
相关问题