Python循环正在从MYSQL数据库打印两次结果

2024-05-28 20:25:32 发布

您现在位置:Python中文网/ 问答频道 /正文

解决了

结果是我调用了我的脚本json.py并导入了json,因此python脚本调用了自己,因此运行了两次

问题

下面是我的代码,它访问数据库并返回以下数据:

import mysql.connector
import ast
import json

mydb = mysql.connector.connect(
  host="localhost",
  user="root",
  passwd="",
  database="db"
)

mycursor = mydb.cursor()
mycursor.execute("SELECT cast FROM credits LIMIT 2")
myresult = mycursor.fetchall()

for x in myresult:
  dictionary = None
  dictionary = ast.literal_eval(str(x))
  dictionary = ast.literal_eval(dictionary[0])
  for a in dictionary:
    print(a["character"])
    #Need to insert the data into a JSON object here
  print("\n")

然后它以cmd的形式给我这个输出:

Woody (voice)
Buzz Lightyear (voice)
Mr. Potato Head (voice)
Slinky Dog (voice)
Rex (voice)

Alan Parrish
Samuel Alan Parrish / Van Pelt
Judy Sheperd
Peter Shepherd

Woody (voice)
Buzz Lightyear (voice)
Mr. Potato Head (voice)
Slinky Dog (voice)
Rex (voice)

Alan Parrish
Samuel Alan Parrish / Van Pelt
Judy Sheperd
Peter Shepherd

数据被打印了两次?我是python新手,从研究来看,可能是因为缩进,我遗漏了什么吗

更新

问题不是由于数据中的重复记录(已测试)


Tags: 数据import脚本jsonforconnectordictionarymysql

热门问题