繁体   English   中英

使用Python将大型CSV文件导入MySQL

[英]Import Large CSV File into MySQL using Python

我正在尝试使用python 3.7将大型CSV文件的一列导入MySQL。 这是作为导入其余列的测试运行而完成的。

现在,我什至无法将一列输入数据库。 我希望能找到帮助。

我已经建立了一个数据库,其中只有一个表,并且只有一个字段用于测试数据:

mysql> use aws_bill
Database changed

mysql> show tables;
+--------------------+
| Tables_in_aws_bill |
+--------------------+
| billing_info       |
+--------------------+

mysql> desc billing_info;
+----------+---------+------+-----+---------+-------+
| Field    | Type    | Null | Key | Default | Extra |
+----------+---------+------+-----+---------+-------+
| RecordId | int(11) | NO   |     | NULL    |       |
+----------+---------+------+-----+---------+-------+

当我运行代码时:

mydb = mysql.connector.connect(user='xxxx', password='xxxxx',
                            host='xxxxx',
                            database='aws_bill')
cursor = mydb.cursor()
try:
    with open(source) as csv_file:
        csv_reader = csv.reader(csv_file, delimiter=',')
        sql = "INSERT INTO billing_info (RecordId) VALUES (%s)"
        for row in csv_reader:
            row = (', '.join(row))
            print(row)
            cursor.execute(sql, row)
except:
    mydb.rollback()
finally:
    mydb.close()

CSV列中只有一行被打印出来:

python3 .\aws_billing.py
200176595756546201775238333

没有任何东西进入数据库:

mysql> select RecordId from billing_info;
Empty set (0.00 sec)

如果我注释掉sql插入语句: cursor.execute(sql, row)

然后打印出CSV的所有行:

203528424494971448426778962
203529863341009197771806423
203529974021473640029260511
203530250722634745672445063
203525214761502622966710100
203525122527782254417348410
203529365278919207614044035
...continues to the end of the file

但是,当然没有数据可以进入数据库。 因为SQL行已被注释掉。 至少现在已经打印了CSV的所有行,但是,将它们放入数据库中会很好!

为什么会这样呢? 如何将CSV的所有行都放入数据库中?

您可以这样做:

将此行sql = "INSERT INTO billing_info (InvoiceId) VALUES (%s)"更改为

sql = "INSERT INTO billing_info (InvoiceId) VALUES {}"

而这一点: cursor.execute(sql, row)cursor.execute(sql.format(row))

暂无
暂无

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

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