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

yipeiwu_com6年前Python基础

如下所示:

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()

以上这篇python将txt文档每行内容循环插入数据库的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python3+PyQt5图形项的自定义和交互 python3实现page Designer应用程序

python3+PyQt5图形项的自定义和交互 python3实现page Designer应用程序

本文通过Python3+PyQt5实现《python Qt Gui 快速编程》这本书的page Designer应用程序,采用QGraphicsView,QGraphicsScene,Q...

Python OpenCV图像指定区域裁剪的实现

在工作中。在做数据集时,需要对图片进行处理,照相的图片我们只需要特定的部分,所以就想到裁剪一种所需的部分。当然若是图片有规律可循则使用opencv对其进行膨胀腐蚀等操作。这样更精准一些。...

Python 串口读写的实现方法

Python 串口读写的实现方法

1.安装pyserial https://pypi.python.org/pypi/pyserial Doc:http://pythonhosted.org/pyserial/ 使用Py...

python调用java的jar包方法

如下所示: from jpype import * jvmPath = getDefaultJVMPath() jars = ["./Firstmaven-1.0-SNAPSHO...

python利用多种方式来统计词频(单词个数)

python的思维就是让我们用尽可能少的代码来解决问题。对于词频的统计,就代码层面而言,实现的方式也是有很多种的。之所以单独谈到统计词频这个问题,是因为它在统计和数据挖掘方面经常会用到,...