Troubleshooting CSV Data Load into MySQL in Python
In attempting to load CSV data into a MySQL table, one may encounter the situation where the code runs without errors, yet the target table remains empty. To resolve this issue, consider the following:
Problem:
import csv import MySQLdb mydb = MySQLdb.connect(host='localhost', user='root', passwd='', db='mydb') cursor = mydb.cursor() csv_data = csv.reader(file('students.csv')) for row in csv_data: cursor.execute('INSERT INTO testcsv(names, \ classes, mark )' \ 'VALUES("%s", "%s", "%s")', row) #close the connection to the database. cursor.close() print "Done"
Solution:
To ensure that the data is successfully inserted into the table, it is necessary to call the mydb.commit() method. This method commits the changes to the database. The corrected code with the necessary modification is:
import csv import MySQLdb mydb = MySQLdb.connect(host='localhost', user='root', passwd='', db='mydb') cursor = mydb.cursor() csv_data = csv.reader(file('students.csv')) for row in csv_data: cursor.execute('INSERT INTO testcsv(names, \ classes, mark )' \ 'VALUES("%s", "%s", "%s")', row) # Commit the data to the database. mydb.commit() #close the connection to the database. cursor.close() print "Done"
The above is the detailed content of Why is My Python MySQL CSV Data Load Failing Despite No Errors?. For more information, please follow other related articles on the PHP Chinese website!