概要
在做数据库迁移的时候通过Python编写了一个比较不同数据库的记录是否相同的小工具,把它分享给大家,希望会对大家有所帮助。
问题场景
由于项目需要把数据库从mysql换成oracle,在做完数据迁移之后需要比较迁移的数据是否相同,我们采用的是通过hash值比较数据是否相同,于是我们就编写了一个Python脚本,用来比较不同数据库生成的hash值是否相同。
相关代码
import argparse
def data_compare(file_path1, file_path2, result_path):
try:
# 清空文件内容
with open(result_path, 'w') as result_file:
result_file.write('数据比较结果:')
result_file.write('\r\n')
with open(file_path1, 'r') as file1:
lines_in_file1 = file1.readlines()
with open(file_path2, 'r') as file2:
lines_in_file2 = file2.readlines()
if len(lines_in_file1) != len(lines_in_file2):
with open(result_path, 'a') as result_file:
print('文件内容的行数不同,请检查。')
result_file.write('\t')
result_file.write('文件内容的行数不同,请检查。')
result_file.write('\r\n')
return
all_same = True
define_header = False
for index, value1 in enumerate(lines_in_file1):
value2 = lines_in_file2[index]
if value1 != value2:
with open(result_path, 'a') as result_file:
if not define_header:
result_file.write('\t')
result_file.write('下面这些是不同的记录:')
result_file.write('\r\n')
define_header = True
result_file.write('\t')
result_file.write('行数: ' + str(index) + '; ')
result_file.write('值1: ' + value1.replace("\n", "") + '; ')
result_file.write('值2: ' + value2.replace("\n", ""))
result_file.write('\r\n')
if all_same:
all_same = False
if not all_same:
print('存在不同的数据,请检查保存结果的文件。')
else:
with open(result_path, 'a') as result_file:
print('所有数据都相同。')
result_file.write('\t')
result_file.write('所有数据都相同。')
except Exception as e:
print("数据比较失败:", e)
# 创建命令行参数
parser = argparse.ArgumentParser(description="比较输入的不同文件中的数据")
parser.add_argument("--file_path1", help="文件1的路径")
parser.add_argument("--file_path2", help="文件2的路径")
parser.add_argument("--result_path", help="保存比较结果的文件路径")
# 解析参数
args = parser.parse_args()
# 调用方法
data_compare(args.file_path1, args.file_path2, args.result_path)
使用方式
假设保存文件为data_compare.py。
在命令行执行如下命令:
python data_compare.py --file_path1 文件1路径 --file_path2 文件2路径 --result_path 保存结果的文件路径