Home > Database > Mysql Tutorial > How Can I Successfully Load CSV Data into MySQL Using Python?

How Can I Successfully Load CSV Data into MySQL Using Python?

Mary-Kate Olsen
Release: 2024-11-28 12:09:10
Original
326 people have browsed it

How Can I Successfully Load CSV Data into MySQL Using Python?

Loading CSV Data into MySQL Using Python

In Python, importing CSV files into MySQL can be accomplished using the MySQLdb library. However, it's crucial to pay attention to the potential pitfalls to ensure successful data loading.

One common issue faced by developers is data not appearing in the target table despite the code running without errors. In this scenario, the cause may lie in the omission of the mydb.commit() command.

This command commits the changes made to the database. Without executing this command, the data may remain in an uncommitted state and will not be visible in the table. Including this command ensures that the changes are permanently persisted into the database.

To illustrate this, consider the following modified code:

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)
mydb.commit() # Commit the changes to the database
cursor.close()
print "Done"
Copy after login

By incorporating the mydb.commit() command, you can effectively load the CSV data into your MySQL table and ensure that it becomes accessible for future queries and operations.

The above is the detailed content of How Can I Successfully Load CSV Data into MySQL Using Python?. For more information, please follow other related articles on the PHP Chinese website!

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