简体   繁体   English

在 Python 中将 CSV 数据加载到 MySQL

[英]Load CSV data into MySQL in Python

Not sure what I'm missing here but this code runs without any error message, but there's nothing in the table.不确定我在这里遗漏了什么,但此代码运行时没有任何错误消息,但表中没有任何内容。 I'm loading a CSV values in three columns into mysql table我正在将三列中的 CSV 值加载到 mysql 表中

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"

Would appreciate if someone else could have a look.如果其他人可以看看,将不胜感激。

I think you have to do mydb.commit() all the insert into.我认为您必须将mydb.commit()全部插入。

Something like this像这样的东西

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.
mydb.commit()
cursor.close()
print "Done"

If you do not have the pandas and sqlalchemy libraries, import using pip如果您没有pandassqlalchemy库,请使用 pip 导入

pip install pandas
pip install sqlalchemy

We can use pandas and sqlalchemy to directly insert into the database我们可以使用pandassqlalchemy直接插入数据库

import csv
import pandas as pd
from sqlalchemy import create_engine, types

engine = create_engine('mysql://root:*Enter password here*@localhost/*Enter Databse name here*') # enter your password and database names here

df = pd.read_csv("Excel_file_name.csv",sep=',',quotechar='\'',encoding='utf8') # Replace Excel_file_name with your excel sheet name
df.to_sql('Table_name',con=engine,index=False,if_exists='append') # Replace Table_name with your sql table name

The above answer seems good.上面的答案看起来不错。 But another way of doing this is adding the auto commit option along with the db connect.但另一种方法是添加自动提交选项以及数据库连接。 This automatically commits every other operations performed in the db, avoiding the use of mentioning sql.commit() every time.这会自动提交在数据库中执行的所有其他操作,避免每次都使用提及sql.commit()

 mydb = MySQLdb.connect(host='localhost',
        user='root',
        passwd='',
        db='mydb',autocommit=true)
  from __future__ import print_function
import csv
import MySQLdb

print("Enter  File  To Be Export")
conn = MySQLdb.connect(host="localhost", port=3306, user="root", passwd="", db="database")
cursor = conn.cursor()
#sql = 'CREATE DATABASE test1'
sql ='''DROP TABLE IF EXISTS `test1`; CREATE TABLE test1 (policyID int, statecode varchar(255), county varchar(255))'''
cursor.execute(sql)

with open('C:/Users/Desktop/Code/python/sample.csv') as csvfile:
    reader = csv.DictReader(csvfile, delimiter = ',')
    for row in reader:
        print(row['policyID'], row['statecode'], row['county'])
        # insert
        conn = MySQLdb.connect(host="localhost", port=3306, user="root", passwd="", db="database")
        sql_statement = "INSERT INTO test1(policyID ,statecode,county) VALUES (%s,%s,%s)"
        cur = conn.cursor()
        cur.executemany(sql_statement,[(row['policyID'], row['statecode'], row['county'])])
        conn.escape_string(sql_statement)
        conn.commit()

using pymsql if it helps如果有帮助,请使用 pymsql

import pymysql
import csv
db = pymysql.connect("localhost","root","12345678","data" )

cursor = db.cursor()
csv_data = csv.reader(open('test.csv'))
next(csv_data)
for row in csv_data:
    cursor.execute('INSERT INTO PM(col1,col2) VALUES(%s, %s)',row)

db.commit()
cursor.close()

If it is a pandas data frame you could do:如果它是一个熊猫数据框,你可以这样做:

Sending the data发送数据

csv_data.to_sql=(con=mydb, name='<the name of your table>',
  if_exists='replace', flavor='mysql')

to avoid the use of the for .避免使用for

Fastest way is to use MySQL bulk loader by "load data infile" statement.最快的方法是通过“load data infile”语句使用MySQL批量加载器。 It is the fastest way by far than any way you can come up with in Python.到目前为止,它是您在 Python 中能想到的任何方法中最快的方法。 If you have to use Python, you can call statement "load data infile" from Python itself.如果必须使用 Python,则可以从 Python 本身调用语句“load data infile”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM