【问题标题】:Python Loop is printing result Twice from MYSQL databasePython Loop 正在从 MYSQL 数据库打印结果两次
【发布时间】:2020-02-11 16:17:40
【问题描述】:

解决了!

原来我调用了我的脚本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 和研究的新手,可能有缩进,我错过了什么吗?

更新

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

【问题讨论】:

  • 您正在执行限制为 2 的查询 - 所以看起来您的数据库中的前两个条目是相同的。
  • @Daniel 我通过订购请求和检查数据对此进行了测试,我可以确认它仍在重复,没有重复记录

标签: python mysql dictionary printing abstract-syntax-tree


【解决方案1】:

我找到了解决办法,

我调用了我的脚本json.py,然后导入了json,所以我认为脚本正在调用自己,因此运行了两次。

我重命名了我的脚本,问题已解决!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-14
    • 2016-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-08
    • 1970-01-01
    • 2019-06-15
    相关资源
    最近更新 更多