python实现将json多行数据传入到mysql中使用

yipeiwu_com6年前Python基础

将json多行数据传入到mysql中使用python实现

表需要提前创建,字符集utf8 如果不行换成utf8mb4

import json
import pymysql

def reviewdata_insert(db):
  with open('data.txt', encoding='utf-8') as f:
    i = 0
    while True:
      i += 1
      print(u'正在载入第%s行......' % i)
      try:
        lines = f.readline() # 使用逐行读取的方法
        review_text = json.loads(lines) # 解析每一行数据
        result = []
        result.append((review_text['id'], review_text['created_at'], review_text['content'],
                review_text['source'], review_text['reports_count'], review_text['comments_count'],
                review_text['attitudes_count']))
        print(result)

        inesrt_re = "insert into review(id,created_at,content,source,reports_count,comments_count,attitudes_count) values(%s,%s,%s,%s,%s,%s,%s)"
        cursor = db.cursor()
        cursor.executemany(inesrt_re, result)
        db.commit()
      except Exception as e:
        db.rollback()
        print(str(e))
        break


if __name__ == "__main__": # 起到一个初始化或者调用函数的作用
  db = pymysql.connect("192.168.67.41", "root", "123456", "data", charset='utf8')
  cursor = db.cursor()
  reviewdata_insert(db)
  cursor.close()

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python关于excel和shp的使用在matplotlib

Python关于excel和shp的使用在matplotlib

关于excel和shp的使用在matplotlib 使用pandas 对excel进行简单操作 使用cartopy 读取shpfile 展示到matplotlib中 利用s...

python交易记录链的实现过程详解

python交易记录链的实现过程详解

接着上篇的内容,这里实现一个交易记录链,废话不多说,先看图: 跟之前的逻辑类似,但也有少许不同,这里多了一个payloadhash,以及对payloadhash和prehash的has...

Python列表list排列组合操作示例

本文实例讲述了Python列表list排列组合操作。分享给大家供大家参考,具体如下: 排列 例如: 输入为 ['1','2','3']和3 输出为 ['111','112','11...

在Python中使用dict和set方法的教程

在Python中使用dict和set方法的教程

dict Python内置了字典:dict的支持,dict全称dictionary,在其他语言中也称为map,使用键-值(key-value)存储,具有极快的查找速度。 举个例子,假设要...

解决python 读取 log日志的编码问题

解决python 读取 log日志的编码问题

1.我要读取log日志的”执行成功”的个数,log日志编码格式为GBK 2.显示报错,大致意思是说utf-8的代码不能解析log日志 3.后来想想把log日志用GBK编码读出来,写到...