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
Release: 2024-11-27 20:34:13
Original
907 people have browsed it

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"
Copy after login

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"
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template