我正在尝试使用Python3.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 insert语句:cursor.execute(sql, row)
然后打印出CSV的所有行:
203528424494971448426778962
203529863341009197771806423
203529974021473640029260511
203530250722634745672445063
203525214761502622966710100
203525122527782254417348410
203529365278919207614044035
...continues to the end of the file但是,当然,这些数据都没有进入数据库。因为SQL行被注释掉了。至少CSV的所有行现在都打印出来了,但是,将它们放到数据库中会更好!
为什么会发生这种情况?如何将CSV的所有行都放入数据库?
发布于 2019-04-29 01:52:09
你可以这样做:
将此行sql = "INSERT INTO billing_info (InvoiceId) VALUES (%s)"更改为
sql = "INSERT INTO billing_info (InvoiceId) VALUES {}"
还有这个:从cursor.execute(sql, row)到cursor.execute(sql.format(row))
https://stackoverflow.com/questions/55892860
复制相似问题