1 将CSV文件数据写入MySQL
Supplier Name Invoice Number Part Number Cost Purchase Date
Supplier X 001-1001 2341
500.001/20/14SupplierX001−10012341
500.00
1
/
20
/
14
S
u
p
p
l
i
e
r
X
001
−
1001
2341
500.00 1/20/14
Supplier X 001-1001 5467
750.001/20/14SupplierX001−10015467
750.00
1
/
20
/
14
S
u
p
p
l
i
e
r
X
001
−
1001
5467
750.00 1/20/14
Supplier Y 50-9501 7009
250.001/30/14SupplierY50−95017009
250.00
1
/
30
/
14
S
u
p
p
l
i
e
r
Y
50
−
9501
7009
250.00 1/30/14
Supplier Y 50-9505 6650
125.002002/3/14SupplierY50−95056650
125.00
2002
/
3
/
14
S
u
p
p
l
i
e
r
Y
50
−
9505
6650
125.00 2002/3/14
Supplier Z 920-4803 3321
615.002002/3/14SupplierZ920−48043321
615.00
2002
/
3
/
14
S
u
p
p
l
i
e
r
Z
920
−
4804
3321
615.00 2002/10/14
Supplier Z 920-4805 3321
615.002/17/14SupplierZ920−48063321
615.00
2
/
17
/
14
S
u
p
p
l
i
e
r
Z
920
−
4806
3321
615.00 2/24/14
import csv
import MySQLdb as mysql
import sys
from datetime import datetime,date
input_file='supplier_data.csv'
con=mysql.connect(host='localhost',port=3306,db='my_suppliers',user='root',passwd='123456')
c=con.cursor()
file_reader=csv.reader(open(input_file,'r',newline=''))
header=next(file_reader)
for row in file_reader:
data=[]
for column_index in range(len(header)):
if column_index <4:
data.append(str(row[column_index]).lstrip('$').replace(',','').strip())
else:
a_date=datetime.date(datetime.strptime(str(row[column_index]),'%m/%d/%y'))
a_date=a_date.strftime('%Y-%m-%d')
data.append(a_date)
print(data)
c.execute("""INSERT INTO Suppliers VALUES (%s,%s,%s,%s,%s);""",data)
con.commit()
print("")
c.execute("select * from suppliers")
rows=c.fetchall()
for row in rows:
row_list_output=[]
for column_index in range(len(row)):
row_list_output.append(str(row[column_index]))
print(row_list_output)