MySQL数据库未在我的python代码中执行查询

MySQL database is not executing query in my python code

提问人:user83975 提问时间:3/22/2022 最后编辑:Nickuser83975 更新时间:7/25/2023 访问量:278

问:

我已经编写了 Python 代码来通过 for 循环更新我的 MySQL 数据库,但是当我运行代码时,它不会将数据插入表中。这是我的代码:

connection = mysql.connector.connect(\*\*db)  # \*\*

cursor = connection.cursor()

for i in range(len(alumniNames)):

    currentName = alumniNames[i]
    query = (f'INSERT INTO alumni (name, address, hometown, state, country, home_phone, mobile_phone) VALUES ("{currentName}", "{alumniInfo[currentName][2]}", "{alumniCities[i]}", "{alumniStates[i]}", "{alumniInfo[currentName][5]}", "{alumniInfo[currentName][7]}", "{alumniInfo[currentName][8]}")')
    
    values = (currentName, alumniInfo[currentName][2], alumniCities[i], alumniStates[i],
              alumniInfo[currentName][5], alumniInfo[currentName][7], alumniInfo[currentName][8])
    
    cursor.execute(query)
    print(f"Query {i + 1} Completed.")
    
    if i % 50 == 0:
        time.sleep(1)

results = cursor.fetchall()

cursor.close()
connection.close()

当我运行代码时,没有数据入到表中。此外,print 语句在 331 处停止(例如,“查询 331 已完成”。

我试图在谷歌上搜索这个问题,但我无法得出结论,为什么会发生这种情况。

python mysql 谷歌云平台

评论


答:

0赞 Nik Wehr 3/22/2022 #1

根据您的代码,您可能正在寻找配置。如果你是python + mysql的新手,我建议你看看SQL Alchemy和Alembic;它会升级你的游戏。autocommit

评论

0赞 user83975 3/22/2022
这行得通,谢谢!你知道为什么它停在 330 个条目吗?
0赞 Nik Wehr 3/22/2022
嗯,不是真的。我会设置断点并检查。
0赞 Nik Wehr 3/22/2022 #2

另外,为了好玩,您可以稍微减少代码。我用了所有 - 时间!:-)enumerate

# instead of range+len
for i, currentName in enumerate(alumniNames):
    ....
0赞 Raghul 7/25/2023 #3

尝试插入

connection.commit() 之前的 connection.close()