"> ');

python,读取文件解析,写入数据库

quange 2024-8-19 1,606 8/19

最近在网上下载到了,qq绑定手机号的数据,试着写入数据库中

python,读取文件解析,写入数据库
import json
import mysql.connector

file_path = r'D:\tens\tencent.txt'

# 数据库连接
db = mysql.connector.connect(
    host="192.168.1.8",  # 数据库主机
    user="social_engineering",  # 数据库用户名
    password="X",  # 数据库密码
    database="social_engineering"  # 数据库名
)

cursor = db.cursor()

with open(file_path, 'r', encoding='utf-8') as file:
    for line in file:
        # 处理每一行
        try:
            # 解析 JSON 数据
            data = json.loads(line.strip())
            _id = data["_id"]
            email_address = data["_source"]["email_address"]
            phone = data["_source"]["phone"]
            qq = data["_source"]["qq"]

            # 插入数据
            insert_query = '''
            INSERT INTO qq (_id, email_address, phone, qq) 
            VALUES (%s, %s, %s, %s)
            '''
            data_to_insert = (_id, email_address, phone, qq)

            cursor.execute(insert_query, data_to_insert)

        except mysql.connector.Error as err:
            print(f"插入数据时出错: {err}")
            db.rollback()  # 回滚更改,防止不完整数据
        except json.JSONDecodeError as json_err:
            print(f"解析 JSON 时出错: {json_err}")
            continue  # 对于无效的 JSON 行,跳过处理

        # 提交所有更改
        db.commit()  # 提交到数据库

# 关闭数据库连接
cursor.close()
db.close()
- THE END -
最后修改:2024年8月19日
0

版权声明:
一、本站致力于为软件爱好者提供国内外软件开发技术和软件共享,着力为用户提供优资资源。
二、本站提供的所有下载文件均为网络共享资源,请于下载后的24小时内删除。如需体验更多乐趣,还请支持正版。
三、我站提供用户下载的所有内容均转自互联网。如有内容侵犯您的版权或其他利益的,请编辑邮件并加以说明发送到站长邮箱。站长会进行审查之后,情况属实的会在三个工作日内为您删除。

共有 0 条评论