网络编程
位置:首页>> 网络编程>> 数据库>> python将txt文档每行内容循环插入数据库的方法

python将txt文档每行内容循环插入数据库的方法

作者:苏宝宝s  发布时间:2024-01-25 21:37:29 

标签:python,txt,数据库

如下所示:


import pymysql
import time
import re

def get_raw_label(rece):
re1 = r'"([\s\S]*?)": "'           #-------------正则表达式
reg1 = re.compile(re1)            # ------------编译一下
str1 = reg1.findall(rece)
return str1

def get_detail(rece):
re2 = r'": "([\s\S]*?)",'           #-------------正则表达式
reg1 = re.compile(re2)            # ------------编译一下
str2 = reg1.findall(rece)
return str2

def a_file(file,cur):
model1= 29
f = open(file, 'r', encoding='UTF-8')
lines = f.readlines()    #readlines() 方法用于读取所有行(直到结束符 EOF)并返回列表,该列表可以由 Python 的 for... in ... 结构进行处理.保存给lines

for line in lines:     #循环执行每一行的内容
 model1+=1
 raw_label1 = get_raw_label(line)
 detail1 = get_detail(line)

# 插入数据
 sql = """insert into models(create_time,model_id,raw_label,detail) values (now(),%s,%s,%s)"""
 cur.execute(sql,[model1,raw_label1,detail1])
 db.commit()

db = pymysql.connect("localhost","root","subaobao666","newdatabase" ) #直接连入newdatabase库
cur = db.cursor() #获取游标

a_file("e:/Desktop/json1.txt",cur)

db.close()

来源:https://blog.csdn.net/qq_42231605/article/details/83417698

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com