python script 生成sql 进行多个数据库合并 | 郑州计算机学校_郑州电脑学校_郑州电脑培训

  对有相同表结构的数据库合并,为了保持主外键关系,比较省事的做法是对各个数据库主外键都加上1000000,这样就能保证新导入数据不会冲突  sql生成from prudential.cms.models import *from django.db.models import get_app, get_modelsAPP = get_app(“cms”)IGNORE_MODELS = [GlobalSettings, Carrier]def get_model_fields(model):return model._meta.fieldsdef main():PREFIX_NUM = 1000000company_list = cmsCompany.objects.all()user_list = cmsUser.objects.all()estate_list = estate.objects.all()cms_list = get_models(APP)for table in cms_list:print “update `%s` set `id` = id + 1000000;” % table._meta.db_tablefield_list = get_model_fields(table)for field in field_list:if type(field) is models.ForeignKey:print “update `%s` set `%s_id` = %s_id + 1000000; ” % (table._meta.db_table,field.name,field.name)main()  导出ID加好后的数据mysqldump -u root -p temp_server5_db –no-create-info –complete-insert table_name table_name2 >change_id_db.sql  合并到相应数据库mysql -u root -p temp_db < change_id_db.sql