Loading... # 引言 数据同步时对方给的是dat文件,格式看不出什么,以文本形式打开,发现是|+|作为的分隔符,目前需要把对方的数据导入到我们的数据库中,故写此脚本。 # 代码 ```python # -*- coding: UTF-8 -*- from PythonFiles import LoggerPlus import pymysql _dbhelper=dbHelper.SQL() start_point = 0 i = 0 db_name = '数据库名称' tablename='表名称' if __name__ == '__main__': driver = pymysql.Connect(host='MySQL服务器地址', user='MySQL服务用户名', password='MySQL服务密码', database=db_name) c = driver.cursor() with open("文件路径", mode='r', encoding='utf-8', errors='ignore') as f: data = [] i = 0 sql = f"INSERT INTO {db_name }.{tablename} VALUES " for line in f: i = i + 1 b = line.split("\n")[0][0:-3].split("|+|") # 分隔符 每行结尾存在3个标识字符,去掉。 # sec = 0 # for j in b: # print(sec, j,b.__len__()) # sec += 1 # import sys # sys.exit() # print(b.__len__()) if i < start_point: continue b[42] = b[42][0:4]+"-"+b[42][4:6]+"-"+b[42][6:8]+b[42][8:] # 此处需要自行修改,对于某一列的格式整理 b = b.__str__().replace( "[", '(').replace("]", '),').replace("''", 'null').replace("'--'",'null') sql += b if i % 5000 == 0: print(i) try: # sql[0:-1] # commit c.execute(sql[0:-1]) driver.commit() sql = f"INSERT INTO {db_name}.{tablename} VALUES " # pass except Exception as e: print(e) pass if sql != f"INSERT INTO {db_name}.{tablename} VALUES ": c.execute(sql[0:-1]) driver.commit() ``` # 结语 对于不同需求,需要自行修改,此文章提供一种解决方案,但是并不适用所有场景。 © 允许规范转载 打赏 赞赏作者 支付宝微信 赞 如果觉得我的文章对你有用,请随意赞赏