网站建设类有哪些职位,佛山 网站关键词优化,wordpress微信接入,全国最好的网站建设案例需要合并的多个PG数据库表个数和结构一致#xff0c;这里提供一种思路#xff0c;选择sql语句insert插入的方式进行#xff0c;即将其他PG数据库的每个表内容插入到一个PG数据库中完成数据库合并
示例代码说明#xff1a;
选择一个数据库导出表结构为.sql文件#xff08…需要合并的多个PG数据库表个数和结构一致这里提供一种思路选择sql语句insert插入的方式进行即将其他PG数据库的每个表内容插入到一个PG数据库中完成数据库合并
示例代码说明
选择一个数据库导出表结构为.sql文件可借助Navicat工具在此基础上修改.sql内容加入insert语句和dblink语句数据可能存在重复需要在每个insert插入语句后带上ON CONFLICT DO NOTHING; 数据库名设置为一个通用变量修改好后的.sql文件就是一个样本文件。复制一个pg数据库并修改名称作为总库总库需要添加dblink扩展批量将.sql样本文件中的数据库名替换为其他要合并的数据库名并另存为新的.sql文件再批量执行每个.sql文件即可。.sql文件修改另存可参考文章【数据处理_Python】使用python脚本将模板文件修改内容后重命名另存为新文件
import psycopg2
import subprocess
import os
def publicsql(old_string,input_sql,input_dir,output_dir):with open(input_sql, r) as infile:content infile.read()for filename in os.listdir(input_dir):if filename.endswith(.sql):nameparts filename.split(.)new_string nameparts[0]# 执行替换操作new_content content.replace(old_string, new_string)# 写入新文件output_file_path os.path.join(output_dir, new_string .sql)with open(output_file_path, w) as oufile:oufile.write(new_content)oufile.close()infile.close()
# 要替换的字段
old_string database
# 样本文件
input_sql rE:\test\public.sql
# 读取替换字段文件路径
input_dir E:/test/chongqinghq/
# 修改文件后输出路径
output_dir E:/test/publicsql/
publicsql(old_string,input_sql,input_dir,output_dir)
#数据库连接信息
database_name hqdb_500100_20241112 #总库名称
username postgres
password postgres
host localhost
port 5432
os.environ[PGPASSWORD] password
# 获取文件夹下所有.sql文件名称
filenames os.listdir(output_dir)
# 遍历文件列表
for filename in filenames:output_file output_dir filenamecommandimport fD:/Program Files/PostgreSQL/10/bin/psql -h {host} -p {port} -U {username} -d {database_name} -f {output_file}subprocess.run(commandimport, checkTrue)print(fDatabase {filename} was successfully imported into Database {database_name})
输出结果示例 .sql样本文件示例