import pymysql
#json文件中格式一个列表包含一个个的字典数据
#[{"title": "胖猫事件-21岁游戏代练胖猫跳江身亡,PUA捞女女主谭竹遭网友报告视频", "cover": "https://suvip888.com/20240516/U8NEMN2P/1.jpg", "m3u8_url": "https://vodvip888.com/20240516/U8NEMN2P/453kb/hls/index.m3u8"}...]
#在数据库创建表
def create_mysql_dbtable(table_name):
# 填写host user password db
db = pymysql.connect(
host="127.0.0.1",
user="root",
password="123456",
db="spider"
# port = 3306, # 数据库端口号
)
cursor = db.cursor()
# sql例子 sese_db表名 下面的就是字段数据 id自增
sql = f"""
create table if not exists {table_name} (
id INT AUTO_INCREMENT PRIMARY KEY,
title varchar(255) not null,
cover varchar(255) not null,
m3u8_url varchar(255) not null
)
"""
cursor.execute(sql)
db.close()
将下载的json数据 写入到数据库中
def write_mysql_data(host, user, passwd, db, table_name):标签:m3u8,写入,db,cursor,json,dict,mysql,data From: https://www.cnblogs.com/Lhptest/p/18290702
# 读取json文件数据,转成字典
data = open("file.json", encoding="utf-8").read()
data_dict_list = json.loads(data)
db = pymysql.connect(host=host, user=user, passwd=passwd, db=db)
cursor = db.cursor()
sql = f"INSERT INTO {table_name}(title,cover,m3u8_url) values (%s,%s,%s)"
for data_dict in data_dict_list:
values = (data_dict["title"], data_dict["cover"], data_dict["m3u8_url"])
cursor.execute(sql, values)
db.commit()
db.close()