python实现将json多行数据传入到mysql中使用
人气:0将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()
您可能感兴趣的文章:
加载全部内容