I have written Python code to update my MySQL database via a for loop, however when I run the code, it does not insert the data into the table. Here is my code:
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()
When I run my code, no data gets inserted into the table. Also, the print statement stops at 331 (ex. "Query 331 Completed.").
I tried to googling the issue but I can't come to a conclusion as to why this is happening.
CodePudding user response:
Based on your code, you're probably looking for autocommit
configuration. If you're new to python mysql, I'd recommend checking out SQL Alchemy and Alembic; it will level up your game.
- https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlconnection-autocommit.html
- https://www.sqlalchemy.org/
- https://alembic.sqlalchemy.org
CodePudding user response:
Also, just for fun you can reduce the code a bit. I use enumerate
all - the - time! :-)
# instead of range len
for i, currentName in enumerate(alumniNames):
....