Home >Database >Mysql Tutorial >Why is My Python MySQL CSV Data Load Failing Despite No Errors?

Why is My Python MySQL CSV Data Load Failing Despite No Errors?

Linda Hamilton
Linda HamiltonOriginal
2024-11-27 20:34:13968browse

Why is My Python MySQL CSV Data Load Failing Despite No Errors?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn